thesystem thesystem - 2 years ago 122
Javascript Question

Simple API call (CORS) not working

First and foremost, I am new to working with APIs.

I am trying to make the most basic API call to a different domain (weather service) than my own, client-side. Among others, I had problems with CORS, not having a correct header present, etc., so I tried to make a workaround by directing the call through crossorigin.me (will be evident from the URL in my code).

(This is not the code, but only the problem - scroll down for code) However, my code currently results in...

console.log(status); //returns 0
console.log(statusText); //returns an empty string


This is the full code.



function createCORSRequest(method, url) {
xhr = new XMLHttpRequest();

//I work in Chrome, so I only included withCredentials, not accounting for other browsers
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
}
xhr.send();
console.log(xhr.status); //returns 0
console.log(xhr.statusText); //returns empty string
}

createCORSRequest("GET", "https://crossorigin.me/https://www.metaweather.com/api/location/2459115");





If you visit the site directly, https://crossorigin.me/https://www.metaweather.com/api/location/2459115, I get this message: Origin: header is required. In console, it gives status code 403 - but I read that only the server can control/access the header, and that I (the coder) can't, so yeah....

Really hope anyone can help or guide me in the right direction, been stuck on this problem for a few days now researching on my own. Thanks in advance.

Answer Source

You are calling xhr.send() and then immediately trying to read the status of the response.

You have to wait until there is a response before you can do that.

Use a load event listener.

xhr.addEventListener("load", log_status);
xhr.send();

function log_status() {
   console.log(this.status);
   console.log(this.statusText);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download