Access-Control-Allow-Origin否认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无法加载https://accounts.spotify.com/api/token 。 请求的资源上不存在“Access-Control-Allow-Origin”标头。 因此,不允许来源“ http://www.bancadigital.com.br ”访问。

有谁知道我如何访问该服务?

https://accounts.spotify.com/api/token的请求需要在服务器端进行,而不是作为AJAX请求。

这样,您的key (包含应用程序的凭据)将不会公开。 此外,Spotify服务器将能够将请求与访问令牌一起重定向到redirect_uri

另一种方法是使用隐式授权流程 ,您可以在其中运行客户端的所有内容,但不会获得刷新令牌。

我建议您查看Spotify Web API授权指南 , 使用auth示例检查GitHub存储 库,并查看使其更容易实现OAuth流的库和包装器 。