API query blocked by CORS

Asked

Viewed 95 times

-3

Expensive,

I am calling an API, but it is being blocked by CORS. I have installed an extension in my browser that enables and disables CORS. When enabled the API returns the expected data, but when disabling returns the following error in the console:

Access to XMLHttpRequest at 'http://minhaurldaapi/rest/busca?cod=1080' from origin 'http://17.12.4.127' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 

Call code:

  var settings = {
    "url": "http://minhaurldaapi/rest/busca?cod=1080",
    "method": "GET",
     "crossDomain": true,
    "timeout": 0,
    "headers": {
      "accept": "application/json",
      "Access-Control-Allow-Origin":"*",
      "Authorization": "Basic AJeqpLOKkiifhueARIjcmOrij7FEF5iodUhIKCPERWh6"
    },
  };

  $.ajax(settings).done(function (response) {
  json = JSON.stringify(response);
  json2 = JSON.parse(json);

  });

I have looked at several other similar issues, but I have not yet solved the problem. Would anyone have any idea how to solve this impasse ? It would be some configuration in APACHE ?

Thank you

  • You have set up Cors in your api?

  • @adventistaam The API is from an external supplier... I’m just consulting... Could you give more details?

  • So they have to set up their CORS api to accept their client

  • If it is an external API and it is not configured to be consumed from your frontend, you should implement in your backend the communication with them.

  • You can access via Postman or Insomnia?

  • Yes, via Postman I was able to access without problems.

  • Most likely the api should be blocking the source and port of your api

  • Try to follow this reply, turn your attention to the headers

  • I added the following information to the headers: code "Accept": "application/json", "Access-Control-Allow-Origin":"*",

Show 4 more comments

1 answer

0


You can ask the API owner to include the key Access-Control-Allow-Origin in the response header with your domain address or a *. Example:

Access-Control-Allow-Origin: http://seudominio.com or Access-Control-Allow-Origin: *

With this the browser will identify the key and will no longer point out the problem of CORS.

If this is not possible, you can build a proxy in your backend (same domain) to intermediary these requests. In other words, your frontend makes the request to your backend, your backend makes the request to the API and returns the response.

I’m leaving this link which in my opinion gives various details about problems like this.

Browser other questions tagged

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