localhost does not have access to the requested page

5

I'm trying to access a URL in AJAX but is giving the following error:

  

XMLHttpRequest can not load link . At the   'Access-Control-Allow-Origin' header is present on the requested   resource. Origin ' link ' is therefore not allowed   access. Create? Length = 0: 201 Error: [object Object]

My AJAX :

var url = "http://receitaws.com.br/v1/cnpj/MEUCNPJ";
$.ajax({
    url: url,
    dataType: "json",
    type: "GET",
    beforeSend: function (data) {
        console.log("aguarde");
    },
    success: function (data) {
        console.log(data);
    },
    error: function (data) {
        console.log("Erro: " + data);
    }
});

JSON FROM THE PAGE:

        {
        "abertura": "TESTE",
        "atividade_principal": [
        {
        "code": "TESTE",
        "text": "TESTE"
        }
        ],
        "atividades_secundarias": [
        {
        "code": "TESTE",
        "text": "TESTE"
        }
        ],
        "bairro": "TESTE",
        "cep": "TESTE",
        "cnpj": "TESTE",
        "complemento": "",
        "data_situacao": "TESTE",
        "data_situacao_especial": "********",
        "efr": "*****",
        "email": "TESTE",
        "fantasia": "********",
        "logradouro": "TESTEP",
        "motivo_situacao": "",
        "municipio": "TESTE",
        "natureza_juridica": "TESTE",
        "nome": "TESTE",
        "numero": "TESTE",
        "situacao": "ATIVA",
        "situacao_especial": "********",
        "status": "OK",
        "telefone": "TESTE",
        "tipo": "TESTE",
        "uf": "TESTE"
    }
    
asked by anonymous 15.12.2015 / 12:18

5 answers

7

As already mentioned, you're trying to do a XMLHttpRequest , and the% destination% is blocking your request. As stated by the error, you are trying to access the url domain through ' link ', which are separate domains. The site recipe does not have documentation explaining the types of access, but the error is blocked for this type of request.

  

XMLHttpRequest can not load link . In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' link ' is therefore not allowed access. Create? Length = 0: 201 Error: [object Object]

To "bypass" this error, you can create a http://receitaws.com.br/v1/cnpj/MEUCNPJ by returning Action to you, it would look like this:

public JsonResult BuscaCnpj(string cnpj)
        {
            using (var client = new WebClient())
            {
                var url = "http://receitaws.com.br/v1/cnpj/" + cnpj;
                var json = client.DownloadString(url);
                var serializer = new JavaScriptSerializer();
                var model = serializer.Deserialize<dynamic>(json);

                return Json(model, JsonRequestBehavior.AllowGet);
            }
        }

This way you will get the data in json . Note that in this json I'm using dynamic , but it is advisable to create a Model for this data, so it will have typed data and it will be easier for you to work with them.

Once you have done this, just make your request serializer.Deserialize<dynamic>(json); call your ajax , like this:

 $.ajax({
                url: 'BuscaCnpj', //Url da Action Aqui
                data: { cnpj: 'MEUCNPJ' },
                success: function (data) {
                    console.log(data);
                },
                type: 'GET'
            });

Ready, so you will have the result below:

    
15.12.2015 / 13:05
0

Politics of the same origin

Try this on your web.config

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
      <add name="Access-Control-Max-Age" value="1000" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
    
15.12.2015 / 12:37
0

I was also wanting to consume this API, and the same problem was occurring the solution is to specify the dataType. See the example below working

$( document ).ready(function() {

   var param = {};
   param.url = 'https://www.receitaws.com.br/v1/cnpj/' + 53113791000122;
   param.method = 'GET';
   param.success =  function(data){
     console.log(data);
   };
   param.dataType = 'jsonp';
   serviceRest(param);     

});



function serviceRest(param){

    $.ajax({
        url: param.url,
        dataType: param.dataType,
        type: param.method,
        data: param.data,
        success: param.success
    });

}

DEMO:

  $( document ).ready(function() {
      debugger;
    
       var param = {};
       param.url = 'https://www.receitaws.com.br/v1/cnpj/' + 53113791000122;
       param.method = 'GET';
       param.success =  function(data){
         console.log(data);
       };
       param.dataType = 'jsonp';


       serviceRest(param);
      
        
    
  
     
  });



function serviceRest(param){
 
    $.ajax({
    url: param.url,
    dataType: param.dataType,
    type: param.method,
    data: param.data,
    success: param.success
    });

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
15.02.2018 / 18:21
0

The API recipe accepts requests via direct AJAX, the problem is the order of the ajax configuration parameters, the dataType, should come before the type, in this order it works quietly.

$.ajax({
        url: 'https://www.receitaws.com.br/v1/cnpj/53113791000122',
        dataType: 'jsonp',
        type: 'GET',
        success: function (data) {
            console.log(data);
        }
    });
    
22.03.2018 / 13:37
-1

Simply change the url address to relative path instead of static.

Example: var url = "/v1/cnpj/MEUCNPJ"; (if in the same domain.)

If you are in a different domain, the destination site may be preventing you from accessing the external site, which is the error reported by the message. In this case, the other response to edit the host can work as long as the destination does not block it.

    
15.12.2015 / 12:40