尝试访问API时如何使用XMLHttpRequest发送密钥?

时间:2017-04-02 19:09:40

标签: javascript ajax web xmlhttprequest

Hey Guys我想要访问MTA的Web API。我确实有钥匙,但我无法拨打电话,因为我不知道如何正确传递密钥。我用字符串&#34替换了我的真实密钥;这是我的密钥"在下面的代码示例中。

代码

 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();

错误

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.

1 个答案:

答案 0 :(得分:1)

As explained in the documentation,API密钥必须作为名为key的GET参数传递,例如

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

但是,您尝试访问的API未启用跨域访问。它不能直接在Javascript Web应用程序中使用 - 密钥不会产生任何影响。