-1

I'm doing an API call to the Insightly API using this code:

var x = new XMLHttpRequest();
x.open("GET", "https://api.insight.ly/v2.2/Projects/Search?status=in%20progress&brief=false&count_total=false", true);
x.setRequestHeader('Authorization', 'Basic: 'some-basic-key-and-user');
x.send();

console.log(x.status);

but the responsecode output equals 0

I've tried my URL and AuthKey using hurl.it's tool, and it gives back exactly the response I need. I've also tried x.statusText and x.Response

How come my script doesn't give me the output I need?

EDIT:

After trying adding those parameters from Mozilla's documentation (thank you Amy). I still don't get the correct response code.

My code now:

var x = new XMLHttpRequest();
x.open("GET", "https://api.insight.ly/v2.2/Projects/Search?status=in%20progress&brief=false&count_total=false", true);
x.setRequestHeader('Authorization', 'Basic: b4c6c660-e20f-4f31-b90d-b6a11bfe4ef2');


x.onprogress = function () {
  console.log('LOADING', x.status);
};
x.onload = function () {
  console.log('DONE', x.status);
};

x.send();

console.log(x.status);

The response code:

0
LOADING 0

Also I've read through the possible answer, and I still don't know how to fix my mistake, I know why it is asynchronous and why it doesn't work this way, but I don't know how to fix.

Grokify
  • 15,092
  • 6
  • 60
  • 81
tjallo
  • 781
  • 6
  • 25
  • You're ignoring the asynchronous nature of `XMLHttpRequest` and attempting to examine the status before it has completed. –  Jan 04 '18 at 15:04
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Serge K. Jan 04 '18 at 15:08
  • "Before the request is complete, the value of status will be 0. It is worth noting that browsers report a status of 0 in case of XMLHttpRequest errors too." https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/status –  Jan 04 '18 at 15:09
  • Add an event handler for the `error` event. Also look in your browsers dev tools, Network tab. You might be running into CORS. –  Jan 04 '18 at 15:22

1 Answers1

2

First of all, you have unnecessary quote symbol on row 3 (right after some-basic-key-and-user). Second is that insight api doesn't support cross origin resource sharing (CORS for short). You might want to introduce some proxy on the same domain you query data from.