我有一个网络应用程序,允许人们生成与特定艺术家相关的艺术家的歌曲列表。我希望能够连接到用户的 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节点module):
$('#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节点module,但我仍然遇到同样的错误。
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 时,它给了我预期的“您是否授权此应用使用您的 Spotify 信息”表单。
我应该在“scripts.js”中要求“cors”才能工作吗?有人有其他建议吗?