localhost does not have access to the requested page

Asked

Viewed 1,041 times

5

I’m trying to access a URL in AJAX but it’s making the following mistake:

Xmlhttprequest cannot load http://receitaws.com.br/v1/cnpj/MEUCNPJ. In the 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost:50562' is therefore not allowed access. Create? Length=0:201 Error: [Object Object]

mine 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 OF 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"
    }
  • I think it can help you here. http://answall.com/questions/47189/consumer-webservice-de-um-link-external

  • gave the same error @Marconi

  • Tried the $..Getjson and gave the same thing?

  • yes, same bug @Marconi

  • What is the return you get when you open the link on the page? You could edit your question with it, even if it is given fictitious.

  • Probably the destination, being hosted on a website and you are running the script internally with localhost, can not authenticate to get this information, the two pages would be hosted on the same domain?

  • Your Webservice was developed in what technology? You have access to its code?

  • am using . Net MVC @Pedrocamarajunior

  • 1

    I don’t have access to the same code @Pedrocamarajunior

Show 4 more comments

5 answers

8


Like I said, you’re trying to make a Xmlhttprequest, and the url destination is blocking your request. As stated by the error, you are trying to access the domain http://receitaws.com.br/v1/cnpj/MEUCNPJ for 'http://localhost:50562', which are separate areas. The site receitaws does not have documentation explaining the types of access, but the error is blocked this type of request.

Xmlhttprequest cannot load http://receitaws.com.br/v1/cnpj/MEUCNPJ. No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost:50562' is therefore not allowed access. Create? Length=0:201 Error: [Object Object]

To "circumvent" this error, you can create a Action returning the json for 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 serializer.Deserialize<dynamic>(json); i am using Dynamic, but the advisable is you create a Model for this data, so you will have typed data and it will be easier for you to work with them.

Done this, just make your request ajax call his Action, in this way:

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

There, so you get the result below: inserir a descrição da imagem aqui

  • thanks again, it worked perfectly

0

The receitaws API accepts requests via direct AJAX, the problem is the order of ajax configuration parameters, the dataType, must come before the type, in this order works smoothly.

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

0

It was also wanting to consume this API, and was occurring the same problem 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>

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>
  • I am developing in . Net MVC

  • wow, sorry. I’ll help you.

  • Gina, tranquil @durtto

  • your local server is iis?

  • you have a web.config file?

  • have yes @durtto

Show 2 more comments

-1

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

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

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

Browser other questions tagged

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