javascriptajaxxmlhttprequest

How to send a key with a XMLHttpRequest when trying to access an API?


I'm trying to access the Web API for the MTA. I do have the key but I'm unable to make the call since I don't know how to pass the key properly. I replaced my real key with the string "This is my key" in the code sample below:

Code

 var myRequest = new XMLHttpRequest();
    myRequest.open('GET','http://bustime.mta.info/api/siri/vehicle-monitoring.json', 'This is my key');
    myRequest.onload = function(){



var data = JSON.parse(myRequest.responseText);
console.log(data[0].comments);


};
myRequest.send();

Error

XMLHttpRequest cannot load http://bustime.mta.info/api/siri/vehicle-monitoring.json. Redirect from 'http://bustime.mta.info/api/siri/vehicle-monitoring.json' to 'http://api.prod.obanyc.com/api/siri/vehicle-monitoring.json' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.


Solution

  • As explained in the documentation, the API key must be passed as a GET parameter called key, e.g.

    http://bustime.mta.info/api/siri/vehicle-monitoring.json?key=<your key>…
    

    However, the API you are trying to access has not enabled cross-domain access. It cannot be used directly from a Javascript web application -- the key will not make a difference.