javascript 访问控制允许来源被拒绝 Spotify api
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28389699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access-Control-Allow-Origin denied spotify api
提问by Daniel Catini
I'm trying to access to the Spotify API token like so:
我正在尝试像这样访问 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);
},
});
but the service returns the following error:
但服务返回以下错误:
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.
XMLHttpRequest 无法加载https://accounts.spotify.com/api/token。请求的资源上不存在“Access-Control-Allow-Origin”标头。Origin ' http://www.bancadigital.com.br' 因此不允许访问。
Does anyone know how I can access the service?
有谁知道我如何访问该服务?
回答by José M. Pérez
The request to https://accounts.spotify.com/api/token
needs to be made server side and not as an AJAX request.
https://accounts.spotify.com/api/token
需要在服务器端发出请求,而不是作为 AJAX 请求。
This way your key
, which contains the credentials for your application, won't be exposed. Also, the Spotify server will be able to redirect the request to the redirect_uri
together with the access token.
这样key
,包含应用程序凭据的 就不会公开。此外,Spotify 服务器将能够将请求redirect_uri
与访问令牌一起重定向到。
An alternative is to use the implicit grant flowwhere you can run everything client side, but you will not get a refresh token.
另一种方法是使用隐式授权流程,您可以在其中运行客户端的所有内容,但不会获得刷新令牌。
I would recommend you to review the Spotify Web API Authorization Guide, check the GitHub repo with auth examplesand take a look at the libraries and wrappersthat make it easier to implement the OAuth flow.
我建议您查看Spotify Web API 授权指南,检查带有身份验证示例的 GitHub 存储库,并查看可以更轻松地实现 OAuth 流程的库和包装器。