Access-Control-Allow-Origin jQuery Ajax

Asked

Viewed 2,122 times

1

I am trying to access the mail api to calculate freight and get the following msg:

Failed to load 
http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx/CalcPrecoPrazo: No 
'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://site.com' is therefore not allowed access.

my ajax:

          var params = {
                'nCdEmpresa': '',
                'sDsSenha': '',
                'nCdServico': '04014',
                'sCepOrigem': '03638010',
                'sCepDestino': '43810040',
                'nVlPeso': '1',
                'nCdFormato': '1',
                'nVlComprimento': '16',
                'nVlAltura': '5',
                'nVlLargura': '15',
                'nVlDiametro': '0',
                'sCdMaoPropria': 'n',
                'nVlValorDeclarado': '0',
                'sCdAvisoRecebimento': 'n',
                'StrRetorno': 'xml',
                'nCdServico': '40010,41106'
            };

        $.ajax({
            type: "POST",
            url: "http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx/CalcPrecoPrazo",
            data: params,
            dataType : "xml",
            success: function (data) {
                console.log(JSON.stringify(data));
            }
        });
  • 1

    The browser blocks due Cors, to make it work a gambiarra (reverse proxy)

  • @Valdeirpsr how to do ajax with reverse proxy ?

  • 1

    Depends on your server. If so Nginx: https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/

  • Are you the owner of the consuming API? To release CORS, you must have access to the "back-end" API.

  • I think this link will help you a lot https://blog.garstasio.com/you-dont-need-jquery/ajax/#Cors

2 answers

2


I don’t know if it’s impossible, but you can access the Mail API next to the server. If you are using PHP create a file, example: php.

/* Recupere os dados enviados via POST
 * Documentação: https://secure.php.net/manual/en/function.filter-input-array.php
 */
$DADOS = filter_input_array(INPUT_POST);
/* Utilize a função 'http_build_query' para construir a string de consulta
 * Documentação: http://php.net/manual/en/function.http-build-query.php
 * 
 * Utilize a função 'simplexml_load_file' para carregar os dados da API
 * Documentação: http://php.net/manual/en/function.simplexml-load-file.php
 */
$resultado = simplexml_load_file( 'http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?' . http_build_query($DADOS) );
echo json_encode($resultado);

Then just make the requisition:

<h2>Frete:</h2>
<div id="frete"></div>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script>
    $(document).ready(function() {
        var params = {
            'nCdEmpresa': '',
            'sDsSenha': '',
            'nCdServico': '40010,41106',
            'sCepOrigem': '03638010',
            'sCepDestino': '43810040',
            'nVlPeso': '1',
            'nCdFormato': '1',
            'nVlComprimento': '16',
            'nVlAltura': '5',
            'nVlLargura': '15',
            'nVlDiametro': '0',
            'sCdMaoPropria': 'n',
            'nVlValorDeclarado': '0',
            'sCdAvisoRecebimento': 'n',
            'StrRetorno': 'xml',
        };

        $.ajax({
            type: "POST",
            url: "calcula_frete.php",
            data: params,
            success: function(data) {
                var j = JSON.parse(data);
                for (var i = 0; i < j.cServico.length; i++) {
                    $('#frete').append(' \
<div>Código: <b>' + j.cServico[i].Codigo + '</b></div> \
<div>Valor: <b>' + j.cServico[i].Valor + '</b></div> \
<div>Prazo entrega: <b>' + j.cServico[i].PrazoEntrega + '</b></div><br>');
                }
            }
        });
    });
</script>

References

  • good, I’ll try!

-3

If I understand correctly you are doing an Xmlhttprequest for a different domain than your page is (Post Office). Therefore, the browser is blocking this as it normally allows a request from the same source for security reasons. You need to do something different when you want to make a cross-domain request using CORS.

Regular web pages may use the Xmlhttprequest object to send and receive data from remote servers, but they are limited by the same source policy. Extensions are not so limited. An extension can talk to remote servers outside of their origin, provided it first requests cross-source permissions.

Increment your Ajax code:

<script>
  var params = {
                'nCdEmpresa': '',
                'sDsSenha': '',
                'nCdServico': '04014',
                'sCepOrigem': '03638010',
                'sCepDestino': '43810040',
                'nVlPeso': '1',
                'nCdFormato': '1',
                'nVlComprimento': '16',
                'nVlAltura': '5',
                'nVlLargura': '15',
                'nVlDiametro': '0',
                'sCdMaoPropria': 'n',
                'nVlValorDeclarado': '0',
                'sCdAvisoRecebimento': 'n',
                'StrRetorno': 'xml',
                'nCdServico': '40010,41106'
            };

$.ajax({
    url: 'http://ws.correios.com.br/calculador/CalcPrecoPrazo.asmx/CalcPrecoPrazo',
    data: params,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader
});
</script>

If that’s what I understand, then it should work.

  • What is setHeader ?

  • These are the developer-defined html headers, for example beforeSend: Function(xhrObj){ xhrObj.setRequestHeader("Content-Type","application/json"); xhrObj.setRequestHeader("Accept","application/json"); }

  • You set the html header by using Jquery, for example if you set the header in PHP, you use the header("Content-Type:application/json");

  • in type, defines post if the postal service accepts only the post method, and as for beforeSend, this is what should be executed after sending your request, being it optional.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.