如何从承诺中保存 Spotify 用户访问令牌?



我知道这可能很简单,但我正试图通过Spotify api找出我的方法,并且在代码方面遇到了一些困难。我打电话给Spotify的clientIdclientSecret。但是,一旦我设置并在承诺中拥有访问令牌,它就不会告诉我实际上请求获取歌曲或艺术家。我意识到这是因为承诺是异步的,并且代码在后台运行时继续(因此异步(。所以我在其中添加了异步和等待功能,但即使在这之后,我的代码仍然无法正常运行。我正在尝试将其作为节点.js文件运行,因此我在准备好时node app.js运行命令。我似乎无法获取数据并进行设置。任何帮助将不胜感激。

法典:

const SpotifyWebApi = require('spotify-web-api-node');

var clientId = {my-id},        //Placeholder
clientSecret = {my-secret};   //Placeholder
// Create the api object with the credentials
let spotifyApi = new SpotifyWebApi({
clientId: clientId,
clientSecret: clientSecret
});
// Retrieve an access token.
const spotify = async() => {
await spotifyApi.clientCredentialsGrant()
.then(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']);


})
.catch(err => {
console.log('Something went wrong when retrieving an access token', err);
});
}

//I want to do stuff with the code but it does not know the access token at this point still
// Get an artist
spotifyApi.getArtist('2hazSY4Ef3aB9ATXW7F5w3')
.then(function(data) {
console.log('Artist information', data.body);
}, function(err) {
console.error(err);
});


错误:

[Error [WebapiError]: Unauthorized] { statusCode: 401 }

因此,我再次意识到错误来自它是异步的事实,但是由于某种原因,我想不出解决此问题的方法。

在调用设置Spotify的clientId和clientSecret之后,您可以通过将另一个然后阻止链接到承诺来请求获取歌曲或艺术家 然后将歌曲或艺术家请求移入其中然后阻止

我希望这有帮助

const SpotifyWebApi = require('spotify-web-api-node');
var clientId = {my-id},        //Placeholder
clientSecret = {my-secret};   //Placeholder
// Create the api object with the credentials
let spotifyApi = new SpotifyWebApi({
clientId: clientId,
clientSecret: clientSecret
});
// Retrieve an access token.
const spotify = async() => {
await spotifyApi.clientCredentialsGrant()
.then(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']);
})
.then(() => {
// do stuff with the code here
// Get an artist or Song here
spotifyApi.getArtist('2hazSY4Ef3aB9ATXW7F5w3')
.then(function(data) {
console.log('Artist information', data.body);
}, function(err) {
console.error(err);
});
})
.catch(err => {
console.log('Something went wrong when retrieving an access token', err);
});
}

最新更新