Access-Control-Allow-Origin jQuery Ajax

1

I'm trying to access the post office to calculate freight and I 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));
            }
        });
    
asked by anonymous 11.05.2018 / 00:58

2 answers

2

I do not know if this is impossible, but you can access the Post Server API on the server side. If you are using PHP create a file, eg calcula_frete.php

/* Recupere os dados enviados via POST
 * Documentação: https://secure.php.net/manual/pt_BR/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/pt_BR/function.http-build-query.php
 * 
 * Utilize a função 'simplexml_load_file' para carregar os dados da API
 * Documentação: http://php.net/manual/pt_BR/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 request:

<h2>Frete:</h2>
<div id="frete"></div>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script><script>$(document).ready(function(){varparams={'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

13.05.2018 / 07:44
-3

If I understand correctly you are making an XMLHttpRequest for a different domain than your page is (Post Office). Therefore, the browser is blocking this because it normally allows a request to 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 can 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 its source, as long as it first requests cross-source permissions.

Increase 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 it's what I understand, then it should work.

    
13.05.2018 / 06:00