简体   繁体   中英

Overcoming CORS with XMLHttpRequest without JSONP in Vanilla JavaScript

Thank you for taking the time to read my question!

I have spent a few days trying to solve an AJAX request problem. After reading dozens of answers on Stack Overflow, I cannot seem to find a solution. Please help.

I am trying to make a request using XMLHttpRequest method with vanilla JavaScript to receive data in JSON format from the API provided by Dark Sky. This is the URI I am trying to send my request to (exposing my key here is not a problem) Link to a sample API request

The problem is I keep receiving a CORS error. Previously, I have overcome this issue with JSONP requests but this time I am trying to understand if there is a way to avoid using JSONP.

I have tried using headers and that removes the CORS error in the console. However, in the response there is no data sent after the request. This is the request that the browser makes without any headers that results in a CORS error:

function CallAjax() {

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/43.11201,-79.11857", true);
xhr.onload = function () {
    console.log(xhr.responseText);
    alert("sucuess");
};
xhr.send();
}

CallAjax();

Is there a way to make a call to an API does not automatically respond with the header "Access-Control-Allow-Origin"," http://localhost:9000/ " or with a header that would prevent CORS error and include JSON data with the response?

Thank you so much for your help!

After looking into it further, it seems that there are two alternatives to overcome CORS errors when requesting data from APIs that do not allow cross-origin requests.

  1. Make a server-side script that requests the data from the API and then serve that data to the browser.
  2. Use an API proxy service that responds with the appropriate headers that do not trigger CORS errors.

Use fetch(). It deals with CORS by default and saved me a lot of trouble. Here's an example:

 fetch(url, { method: 'post', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, body: JSON.stringify({foo:bar}) }) .then(function (resp){ return resp.json() }) .then(function (data) { console.log('Request succeeded with JSON response', data); }) .catch(function (error) { console.log('Request failed', error); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM