Search code examples
javascriptajaxhttpauthenticationbasic-authentication

What is wrong with my HTTP over AJAX (javascript)


My code: var answer_array = [];

var req = new XMLHttpRequest();
req.onload = function() {
    answer_array = answer_array.concat(JSON.parse(this.responseText).results);

    console.log(answer_array);

}

req.open("GET", "https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13");
req.setRequestHeader("authorization", "Basic Base64 encoded credentials");
req.setRequestHeader("cache-control", "no-cache");
req.setRequestHeader("postman-token", "b94725ff-408b-c82e-a985-6c38feb380af");
req.send();

This is what is in my console: scripts2.js:22 OPTIONS https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13 (anonymous function) @ scripts2.js:22 2015-10-21 12:41:09.059 index.html:1 XMLHttpRequest cannot load https://api.comettracker.com/v1/gpsdata?fromdate=2015-10-13. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.

When I go to the network tab on Chrome I see this: gpsdata?fromdate=2015-10-13 OPTIONS 405 xhr scripts2.js:22 0 B 452 ms


Solution

  • This error message:

    No 'Access-Control-Allow-Origin' header is present on the requested resource
    

    means that you are running into a cross origin permission issue which means that you are trying to access a site that does not permit access from the domain that your page is on. If your page is on your local drive being accessed with a file:// URL, then the first thing you can do is to put it on an actual web server and try it there since file:// URLs have some additional restrictions on them.

    If that doesn't work either, then the issue is that the api.comettracker.com site is not allowing access from your particular site.

    When I put your code into a jsFiddle and try it there and look at the network trace, what I see there is that the OPTIONS method which is used to pre-flight a cross origin request is being rejected by api.comettracker.com which tells the browser the cross origin request as currently formatted is not permitted.

    I get a different error if your custom headers are removed from the request so I think that there's something incorrect about your custom headers. Since I don't know that particular API, don't have your access credentials or know how to use them, I don't know what exactly to suggest for the headers, but I think that's the place to start.