1

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
thesystem
  • 554
  • 1
  • 10
  • 31
  • 1
    You're simply trying to read the status before the request has been sent. You have to wait for the response. – Quentin Jul 27 '17 at 15:09
  • 1
    "but I read that only the server can control/access the header" — HTTP messages have headers. HTTP requests have headers. HTTP responses have headers. The server is complaining that your HTTP request didn't include an `Origin` header. This is because you didn't send it with XMLHttpRequest. – Quentin Jul 27 '17 at 15:10
  • @Quentin on line 2, I am defining xhr as a XMLHttpRequest. Why is it not a XMLHttpRequest then? Thank you very much – thesystem Jul 27 '17 at 15:24
  • 1
    You said "If you visit the site directly … Origin: header is required". You aren't using XMLHttpRequest then. – Quentin Jul 27 '17 at 15:26
  • Ah, of course. I appreciate your help a lot. – thesystem Jul 27 '17 at 15:32

1 Answers1

1

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);
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335