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

Getting Spotify API access token from frontend JavaScript code

本文关键字:Spotify API 访问令牌 获取 代码 前端 JavaScript      更新时间:2023-09-26

我有一个web应用程序,允许人们生成与特定艺术家相关的艺术家的歌曲列表。我希望能够连接到用户的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 server:

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时,它会给我预期的"您是否授权此应用程序使用您的Spotify信息"表单。

我应该要求'cors'在'scripts.js'为它工作吗?有人有其他建议吗?

我认为这里的问题是您试图从应该指向用户的端点检索JSON数据。因此,您应该在页面上提供一个链接到https://accounts.spotify.com/authorize/{...} URL的按钮,而不是向它发出请求。用户将继续向您的应用程序授予您在scope参数中指定的请求权限,并将被定向回您在redirect_uri参数中指定的URL。这是获得授权代码的地方,您可以在https://accounts.spotify.com/api/token/{...}端点中使用该代码。在授权指南中阅读更多关于授权代码流程的信息。

Spotify Web API支持三种不同的oAuth流,您可能对隐式授权感兴趣。使用Node用Javascript编写的所有这些流的示例可在https://github.com/spotify/web-api-auth-examples找到。