javascript - 为什么在 Codecademy React 项目中未定义 jsonResponse 中的属性“id”?
问题描述
我正处于使用 Spotify API 的 Jammming 项目的最后阶段,试图保存用户播放列表(并在此处练习寻求帮助......谢谢!)。问题代码:Spotify.savePlaylist
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,是什么使链jsonResponse
中的下一个then
未定义,这就是您尝试id
从未定义变量中读取的地方。return
之前添加,response.json()
然后重试。
什么时候看不到任何id
属性的原因console.log
response
是因为 id 在该响应的正文中,而正文没有在那里显示console.log
,console.log(response.json())
可能会产生您正在寻找的解析的 json 响应,并且id
会在该对象中。
推荐阅读
- android - 不确定如何处理插入方法的返回类型
- java - 滚动文件没有在第二天创建,前一天的文件正在用新日志写入
- janusgraph - 运行 gremlin 脚本时数据损坏异常
- c# - EF-core OnModelCreating 方法中的依赖注入
- wxwidgets - 在 wxSearchCtrl 上按 Enter 键未按预期触发
- indexeddb - dexie.js:第一次嵌套查询很慢
- mysql - MYSQL的USING子句
- javascript - 在本机反应中将批量照片上传到 Firebase 存储
- c++ - 在 BST heap-use-after-free 错误中删除节点
- angular - 将自定义控件添加到角度选择下拉控件