Client Credentials Flow 适用于 curl 但不适用于浏览器

Client Credentials Flow works with curl but not in browser

我正在开发一个 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 吗?

没有。除非服务器特别授权,否则浏览器不允许 CORS。在您的情况下,您无法控制服务器,因此您只有一个选择 - 破解浏览器。使用 Firefox 和 Chrome 的插件轻松完成。为 Firefox 搜索 CORS Everywhere。有一个 chrome 也叫做 access control allow *,或者类似的东西。

相信我...我花了一个星期尝试不同的 REST api。尝试了 js fetch 等。你必须用插件破解浏览器。