2017-04-02 79 views
-1

嘿,伙计们我正在绑定访问MTA的Web API。我确实有钥匙,但我无法拨打电话,因为我不知道如何正确传递钥匙。我在下面的代码示例中用字符串“This is my key”替换了我的真正密钥。如何在尝试访问API时使用XMLHttpRequest发送密钥?

代码

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. 
+0

“我不知道如何正确传递密钥” - 这取决于API期望密钥的呈现方式。 – Quentin

回答

1

As explained in the documentation,API密钥必须尽可能称为key GET参数,例如通过

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

但是,您尝试访问的API尚未启用跨域访问。它不能直接从JavaScript Web应用程序中使用 - 关键不会产生影响。

相关问题