[英]TypeError when instantiaing SpotifyWebApi object
我正在尝试编写一个机器人来处理 spotify 中的一些播放列表。 我正在使用 spotify-web-api-node package: https://github.com/thelinmichael/spotify-web-api-node
我安装了 package,每当我尝试使用以下代码创建 object 时:
const SpotifyWebApi = require('spotify-web-api-node');
const spotifyApp = SpotifyWebApi();
我不断收到此错误:
this._credentials = credentials || {};
^
TypeError: Cannot set properties of undefined (setting '_credentials')
这是 src 文件中的构造函数签名:
constructor(credentials?: Credentials);
有什么想法吗?
您需要access-token
才能访问 API 调用。
在文档中,
如果您有一个访问令牌并想将它用于所有调用,只需使用 API 对象的 set 方法即可。 授权部分详细描述了处理凭据。
spotifyApi.setAccessToken('<your_access_token>');
演示代码:获取访问令牌然后获取猫王的专辑
const SpotifyWebApi = require('spotify-web-api-node');
const axios = require('axios')
const getToken = async () => {
try {
const response = await axios.post(
url = 'https://accounts.spotify.com/api/token',
data = '',
config = {
params: {
'grant_type': 'client_credentials'
},
auth: {
username: '<your client id>',
password: '<your client secret>'
}
}
);
return Promise.resolve(response.data.access_token);
} catch (error) {
return Promise.reject(error);
}
}
getToken()
.then(token => {
const spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken(token);
// Passing a callback - get Elvis' albums in range [0...1]
spotifyApi.getArtistAlbums('43ZHCT0cAZBISjO8DG9PnE', { limit: 2, offset: 0 }).then(
(data) => {
console.log('Artist albums', data.body);
},
(err) => {
console.error(err);
}
);
})
.catch(error => {
console.log(error.message);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.