我正在尝试调用Spotify API。当我运行Spotify.getSongs()时,出现错误。这是我得到的错误:
TypeError:无法读取未定义的属性“ items”。
但是,当我将getSongs定义为该对象之外的函数时,它可以正常工作。如何拨打“ Spotify.getSongs()”的电话?
let Spotify = {
getOAuth() {
fetch("https://accounts.spotify.com/api/token", {
method: "POST",
body:
"grant_type=client_credentials&client_id=" +
clientId +
"&client_secret=" +
clientSecret,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(function(resp) {
// Return the response as JSON
return resp.json();
})
.then(function(data) {
// Log the API data
console.log("token", data);
// Store token data
this.token = data.access_token;
this.tokenType = data.token_type;
this.expires = new Date().getTime() + data.expires_in * 1000;
})
.catch(function(err) {
// Log any errors
console.log("something went wrong", err);
});
},
getSongs() {
return fetch(
`https://api.spotify.com/v1/search?q=inception%20soundtrack&type=playlist`,
{
headers: {
Authorization: this.tokenType + " " + this.token,
"Content-Type": "application/json"
}
}
)
.then(resp => resp.json())
.then(function(data) {
console.log(data);
let tracks = data.playlists.items[0].href;
return fetch(
`${tracks}/tracks?fields=items(track(name,artists(name),album(name,href)))`,
{
headers: {
Authorization: this.tokenType + " " + this.token,
"Content-Type": "application/json"
}
}
);
})
.then(response => response.json())
.then(data => {
console.log(data);
return data.items.map(info => ({
name: info.track.name,
artist: info.track.artists[0].name,
album: info.track.album.name
}));
});
}
// If current token is invalid, get a new one
// makeCall() {
// if (!this.expires || this.expires - new Date().getTime() < 1) {
// console.log("new call");
// this.getOAuth().then(function() {
// this.getSongs();
// });
// }
// }
};