为什么 jsonResponse 中的属性 'id' 在 Codecademy React 项目中未定义?



我正处于Jamming项目的最后阶段,与Spotify API合作,试图保存用户播放列表(并在这里练习寻求帮助…谢谢!(。问题代码:Spotify.save播放列表

let accessToken;
const clientID = 'XXXXX';
const redirectURI = 'http://localhost:3000/';
const Spotify = {

search(term) {
const accessToken = Spotify.getAccessToken();
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`,
{ headers: { Authorization: `Bearer ${accessToken}` } 
}).then(response => {
return response.json();
}).then(jsonResponse => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map(track => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri
}));
});
},
savePlaylist(name, trackUris) {
if (!name || !trackUris.length) {
return;
};
let accessToken = Spotify.getAccessToken();
let headers = {Authorization: `Bearer ${accessToken}`};
let userID;
return fetch('https://api.spotify.com/v1/me', {headers: headers}
).then(response => {
console.log(response);
response.json();
}).then(jsonResponse => {
userID = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/user/${userID}/playlists`,
{
headers: headers,
method: 'POST',
body: JSON.stringify({name: name})
}).then(response => response.json()
).then(jsonResponse => {
const playlistID = jsonResponse.id;
return fetch(`/v1/users/${userID}/playlists/${playlistID}/tracks`,
{
headers: headers,
method: 'POST',
body: JSON.stringify({uris: trackUris})
})
})
})
},
getAccessToken() {
if (accessToken) {
return accessToken;
}
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
const expiresIn = Number(expiresInMatch[1]);
window.setTimeout(() => accessToken = '', expiresIn * 1000);
window.history.pushState('Access Token', null, '/');
return accessToken;
} else {
const accessURL = `https://accounts.spotify.com/authorize?client_id=${clientID}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
window.location = accessURL;
}
}
};
export default Spotify;

我得到的错误是:未处理的拒绝(TypeError(:无法读取未定义的属性"id"。我的应用程序使用隐式授权流,通过记录API的响应,我看到了:

Response {type: "cors", url: "https://api.spotify.com/v1/me", redirected: false, status: 200, ok: true, …}
body: ReadableStream
locked: true
__proto__: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://api.spotify.com/v1/me"
__proto__: Response

我很困惑,想知道这个似乎没有授予用户访问权限的响应是否让我走上了调试的正确轨道。人们能教我一点吗?再次感谢。

错误表明您尝试从未定义中读取id,而不是id未定义,因此您尝试从中读取id的变量jsonResponse未定义。

仔细查看您的savePlaylist函数,注意您没有从响应中返回json,这是链中下一个then中的jsonResponse未定义的原因,也是您试图从未定义变量读取id的原因。在response.json()之前添加return,然后重试。

console.logresponse时,您之所以看不到任何id属性,是因为id在该响应的主体中,而主体没有显示在console.log中,console.log(response.json())可能会发出您要查找的解析json响应,而id则在该对象中。

最新更新