2015-02-08 74 views
3

我試圖訪問Spotify的API令牌就像這樣:訪問控制允許來源否認了Spotify的API

$.ajax({ 
 
    url: "https://accounts.spotify.com/api/token", 
 
    type: 'POST', 
 
    contentType: "application/json; charset=\"utf-8\"", 
 
    crossDomain: true, 
 
    data: { 
 
    grant_type: "authorization_code", 
 
    code: code, 
 
    redirect_uri: "http://www.bancadigital.com.br/spotifyteste/callback.html" 
 
    }, 
 
    processData: false, 
 
    dataType: "json", 
 
    headers: { 
 
    Authorization: "Basic " + utf8_to_b64(key) 
 
    }, 
 
    success: function(response) { 
 
    alert(response.access_token); 
 
    }, 
 
});

但服務返回以下錯誤:

XMLHttpRequest cannot load https://accounts.spotify.com/api/token . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://www.bancadigital.com.br ' is therefore not allowed access.

有誰知道我該如何訪問該服務?

+0

如果他們不允許你 - 你不能這樣做使用客戶端JS。 – zerkms 2015-02-08 01:59:03

+0

我自己並沒有使用Spotify API,但這個例子可能會有所幫助。 https://github.com/spotify/web-api-auth-examples/blob/master/client_credentials/app.js – Taylor714 2015-02-08 03:01:38

回答

9

https://accounts.spotify.com/api/token的請求需要作爲服務器端,而不是作爲AJAX請求。

這樣你的key,其中包含您的應用程序的憑據,將不會公開。此外,Spotify服務器將能夠將請求與訪問令牌一起重定向到redirect_uri

另一種方法是使用implicit grant flow,您可以在其中運行客戶端的所有內容,但不會獲得刷新令牌。

我建議您查看Spotify Web API Authorization Guide,檢查the GitHub repo with auth examples並查看libraries and wrappers,這可以更容易地實現OAuth流程。