从前端 JavaScript 代码获取 Spotify API 访问令牌

Getting Spotify API access token from frontend JavaScript code

我有一个网络应用程序,允许人们生成与特定艺术家相关的艺术家的歌曲列表。我希望能够连接到用户的 Spotify 帐户并从该歌曲列表中为他们创建播放列表,但我需要获取访问令牌。我有一个开发者帐户和客户端 ID,正在尝试通过授权流程进行工作,但它对我不起作用。相反,我收到此错误:XMLHttpRequest cannot load https://accounts.spotify.com/authorize/?client_id=d137fe25b31c4f3ba9e29d85f…:3000/callback&scope=user-read-private%20user-read-email&state=34fFs29kd09. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

这是我的 scripts.js 文件的一部分(我正在使用 spotify-web-api-js 节点模块):

$('#spotify').on('click', function() {
    $.support.cors = true;
    $.getJSON("https://accounts.spotify.com/authorize/?client_id=d137fe25b31c4f3ba9e29d85f4e47c66&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&scope=user-read-private%20user-read-email&state=34fFs29kd09", function(json2){
    $.getJSON("https://accounts.spotify.com/api/token/?grant_type=authorization_code&code=" + json2.code + "&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&client_id=d137fe25b31c4f3ba9e29d85f4e47c66&client_secret={...}", function(json3) {
      s.setAccessToken(json3.access_token);
      });
    });
  });
});

根据我的研究,这是一个与 CORS 相关的问题。我正在对我的 ExpressJS 服务器进行编辑以解决此跨源问题并安装 cors 节点模块,但我仍然遇到相同的错误。

index.js 服务器:

var express = require('express');
var cors = require('cors');
var app = express();
var port = 3000;

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});


 app.use(express.static(__dirname + '/public')); // looks in public directory, not root directory (protects files)

 app.get('/', function(req, res) {
     res.send(__dirname + '\index.html')
});

app.listen(port, function() {
          console.log('CORS-enabled web server listening on port ' + port);
});

当我直接通过浏览器转到有问题的 URL 时,它给了我预期的 "Do you authorize this app to use your Spotify information" 表单。

我是否应该在 'scripts.js' 中要求 'cors' 才能正常工作?有没有人有任何其他建议?

我认为这里的问题是您正试图从您应该引导用户的端点检索 JSON 数据。因此,与其发出请求,不如在页面上提供一个链接到 https://accounts.spotify.com/authorize/{...} URL. The user will proceed to give your application the permissions you've requested as specified in the scope parameter, and will be directed back to the URL you've specified in the redirect_uri parameter. This is where you get the authorization code, which you can use in the https://accounts.spotify.com/api/token/{...} endpoint. Read more about the Authorization Code flow in the Authorization Guide.

的按钮

Spotify Web API 支持三种不同的 oAuth 流程,您可能对 Implicit Grant. Examples of all of these flows written in Javascript using Node is available at https://github.com/spotify/web-api-auth-examples.

感兴趣