允许前端 JavaScript POST 请求到 https://accounts.spotify.com/api/token 端点
Allowing frontend JavaScript POST requests to https://accounts.spotify.com/api/token endpoint
为了在我的网络应用程序中获得 Spotify API 的访问令牌(由他们的网络授权流程指定),我了解到我必须发出 POST
请求.但是,当我这样做时,由于跨源问题,我得到 XMLHttpRequest
500 Error
。
我已经想出如何允许 CORS GET
请求,但我不确定如何对 POST
请求执行相同的操作。 This link 提供配置提示,但将 GET
和 POST
的实际路由留空。
这是我的 Express.js 服务器的相关代码:
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.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.send(__dirname + '\index.html')
});
app.post('/', function(req, res) {
res.send(req.body.spotify);
});
(spotify
是 spotify-web-api-js
节点模块)。
我之前曾尝试将 app.get
的确切代码复制到 app.post
,但这导致服务器崩溃。
这是我程序的 JavaScript 文件中的一段代码,它打算在用户单击将他们带到 Spotify 授权路径的开头并批准的按钮后发送 POST
请求签到:
$('#spotify').on('click', function() {
$.support.cors = true;
$.post("https://accounts.spotify.com/api/token");
});
(在本例中,spotify
是 HTML 文件中按钮的 ID)
在这种情况下,我应该怎么做才能绕过 CORS 问题?纠结了几天
您可以在 https://github.com/spotify/web-api-auth-examples 上找到使用 Express 与 Spotify 执行身份验证流程的示例(请参阅 authorization_code
方法)。
您无法获得向 /api/token
发出客户端请求的访问令牌。您需要向 /authorize
发出请求,这将重定向到您的 redirect_uri
,它本身将与访问令牌交换 code
。
检查该示例,它应该满足您的需求。
为了在我的网络应用程序中获得 Spotify API 的访问令牌(由他们的网络授权流程指定),我了解到我必须发出 POST
请求.但是,当我这样做时,由于跨源问题,我得到 XMLHttpRequest
500 Error
。
我已经想出如何允许 CORS GET
请求,但我不确定如何对 POST
请求执行相同的操作。 This link 提供配置提示,但将 GET
和 POST
的实际路由留空。
这是我的 Express.js 服务器的相关代码:
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.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.send(__dirname + '\index.html')
});
app.post('/', function(req, res) {
res.send(req.body.spotify);
});
(spotify
是 spotify-web-api-js
节点模块)。
我之前曾尝试将 app.get
的确切代码复制到 app.post
,但这导致服务器崩溃。
这是我程序的 JavaScript 文件中的一段代码,它打算在用户单击将他们带到 Spotify 授权路径的开头并批准的按钮后发送 POST
请求签到:
$('#spotify').on('click', function() {
$.support.cors = true;
$.post("https://accounts.spotify.com/api/token");
});
(在本例中,spotify
是 HTML 文件中按钮的 ID)
在这种情况下,我应该怎么做才能绕过 CORS 问题?纠结了几天
您可以在 https://github.com/spotify/web-api-auth-examples 上找到使用 Express 与 Spotify 执行身份验证流程的示例(请参阅 authorization_code
方法)。
您无法获得向 /api/token
发出客户端请求的访问令牌。您需要向 /authorize
发出请求,这将重定向到您的 redirect_uri
,它本身将与访问令牌交换 code
。
检查该示例,它应该满足您的需求。