【发布时间】:2017-09-06 07:59:11
【问题描述】:
我目前正在学习 Node.js 和 Express,并想构建一个简单的应用程序来查询 Spotify Web API,而无需使用外部库,例如 spotify-web-api-node。我的代码可在https://pastebin.com/Jwe8sckJ获得
我的“/callback”路由是这样的;
app.get("/callback", function(req, res){
res.send("OK!")
var authCode = req.query.code
var options = { method: 'POST',
url: 'https://accounts.spotify.com/api/token',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
form:
{ grant_type: 'authorization_code',
code: authCode,
redirect_uri: 'https://example.com/callback',
client_id: clientId,
client_secret: clientSecret } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
var accessToken = JSON.parse(body).access_token;
var refreshToken = JSON.parse(body).refresh_token
console.log("Access Token: " + accessToken);
console.log("Refresh Token: " + refreshToken);
});
});
到目前为止,一切正常,我能够获得访问令牌和刷新令牌。我感到困惑的部分是我现在如何在“/callback”路由之外使用这些令牌?或者也许另一种询问方式是如何全局保存变量。如果我这样做,是否会对脚本的新会话产生任何影响?
【问题讨论】: