2017-04-02 75 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應用程序中使用 - 關鍵不會產生影響。

相關問題