2017-01-02 52 views
0

我正在開發一個Spotify應用程序,並且我想獲取令牌。客戶端憑證流程使用捲曲但不在瀏覽器中

我下面Client Credentials Flow和使用curl一切正常:

$ curl -H "Authorization: Basic YjU4Y...llYTQ=" \ 
-d grant_type=client_credentials \ 
https://accounts.spotify.com/api/token 
# Response: 
# { 
# "access_token":"BQD3u...W4iJA", 
# "token_type":"Bearer", 
# "expires_in":3600 
# } 

在這裏,有我的HTML文件的Javascript代碼,我試圖得到相同的結果:

var url = "https://accounts.spotify.com/api/token"; 
var authentication = "YjU4Y...llYTQ="; 
var params = { grant_type: "client_credentials" }; 
var auth = "Basic " + authentication; 

$.ajax({ 
    url: url, 
    type: 'POST', 
    dataType: 'json', 
    headers: { 
     'Authorization' : auth, 
     'Access-Control-Allow-Origin': '*' 
    }, 
    data: params, 
    success: function(data) { 
     console.log('success', data); 
    } 
}); 

但是,我收到以下錯誤:

XMLHttpRequest cannot load https://accounts.spotify.com/api/token . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

什麼我做錯了嗎?

真的有一種方法可以從使用Javascript的靜態HTML文件中使用Spotify API嗎?

+0

http://stackoverflow.com/questions/33188989/allowing-cors-jquery-post-requests-to-spotify-api-on-express-js-server/33198424#33198424似乎相關。和https://github.com/spotify/web-api-auth-examples。來自Spotify的http://stackoverflow.com/users/540274/jos%C3%A9-m-p%C3%A9rez似乎圍繞SO回答問題。 – sideshowbarker

+0

謝謝@sideshowbarker,但我不想要任何服務器端代碼。 –

+0

如果您嘗試從客戶端進行身份驗證,那麼爲什麼使用由於CORS而不是隱式授權而需要服務器端應用程序的客戶端憑證?也許我誤解了這個問題。 –

回答

2

沒什麼。瀏覽器不允許CORS,除非服務器明確授權它。在你的情況下,你不控制服務器,所以你只有一個選擇 - 破解瀏覽器。輕鬆完成Firefox和Chrome的插件。搜索適用於Firefox的CORS。還有一個用於訪問控制的chrome也允許*,或者類似的東西。

相信我...我花了一個星期嘗試不同的REST api。試過js抓取等。你必須用插件破解瀏覽器。

+0

但Spotify希望開發人員在這些情況下做什麼?黑客入侵瀏覽器是一個臨時解決方案。 –

+0

我不能說Spotify特別。我從來沒有看過它。看看他們是否發佈了一些API文檔。搜索「CORS」。這是你的問題 - CORS。 –