【发布时间】:2016-01-06 21:01:28
【问题描述】:
我有一个网络应用程序,它允许人们生成与特定艺术家相关的艺术家的歌曲列表。我希望能够连接到用户的 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 时,它会给我预期的“您是否授权此应用使用您的 Spotify 信息”表单。
我是否应该在 'scripts.js' 中要求 'cors' 才能工作?有人有其他建议吗?
【问题讨论】:
标签: javascript jquery express cors spotify