javascript - 使用客户端凭据流刷新 spotify 令牌
问题描述
我已经设置了正确的客户端凭据流,并且可以获取令牌来拨打电话,但是在 3600 之后我想获得新的(我的应用程序仅使用“公共”spotify 端点)我使用https://github.com/thelinmichael/spotify -web-api-node。
对不起我的英语不好。
const express = require('express');
const router = express.Router();
const SpotifyWebApi = require('spotify-web-api-node');
// Create the api object with the credentials
const spotifyApi = new SpotifyWebApi({
clientId: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
clientSecret: 'xxxxxxxxxxxxxxxxxxxxxxxxx'
});
// Retrieve an access token.
spotifyApi.clientCredentialsGrant().then(
function(data) {
console.log('The access token expires in ' + data.body['expires_in']);
console.log('The access token is ' + data.body['access_token']);
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body['access_token']);
// console.log('The refresh token is ' + spotifyApi.getRefreshToken());
},
function(err) {
console.log('Something went wrong when retrieving an access token', err);
}
);
router.get('/getArtistAlbums', function(req, res, next) {
const user_id = req.query['id'];
spotifyApi
.getArtistAlbums(user_id, {
limit: 10,
offset: 20
})
.then(
function(data) {
res.send(data.body);
},
function(err) {
console.error(err);
}
);
});
解决方案
而不是刷新获得的令牌(这在使用 clientCredentialsGrant 时是不可能的,只需请求一个新的令牌。
//This function will create a new token every time it's called
function newToken(){
spotifyApi.clientCredentialsGrant().then(
function(data) {
...
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body['access_token']);
},
function(err) {
... //Error management
}
);
}
//When the app starts, you might want to immediately get a new token
newToken();
//And set an interval to "refresh" it (actually creating a new one) every hour or so
tokenRefreshInterval = setInterval(newToken, 1000 * 60 * 60);
推荐阅读
- google-sheets - 如何在谷歌表格中获得更多位数的多项式趋势线
- altbeacon - iBeacon 传输似乎不稳定,Altbeacon android Kotlin
- amazon-web-services - 是否有任何 AWS CLI 命令来获取特定资源的支持区域列表
- angular - NPM Azure 管道 - 缺少脚本
- python - Selenium 脚本在本地运行,但由于 TimeOutException 在 jenkins 中失败
- php - Laravel 使用经过验证的中间件保护路由不起作用
- user-interface - 我们可以在 Jetson Nano 中使用颤振吗?
- php - 在 PHP 中以字符串形式存储的类上调用静态成员函数?
- php - 双 foreach 循环不会在 cakephp 中循环
- javascript - 单击导航链接或外部时切换导航菜单