我在处理我的 Spotify Web 应用程序时遇到了一个奇怪的错误。我尝试将播放列表保存到我的帐户,它必须获取 id
来自 https://api.spotify.com/v1/me 的元素端点,然后将播放列表应用到您的帐户。否则一切似乎都很好,除了获取到该端点,这会引发错误:
Spotify.js:81 Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)'
我以前从未见过这个错误,我不确定为什么会这样。 findUserId
方法是:
findUserId() {
if(accessToken === undefined) {
this.getAccessToken();
}
console.log(accessToken);
let userId;
fetch(`https://api.spotify.com/v1/me`, {headers: `Bearer ${accessToken}`}
).then(response => {return response.json()}
).then(jsonResponse => {
userId = jsonResponse.id;
});
console.log(userId);
return userId;
}
最佳答案
首先,您必须在 headers
中设置 Authentication
header 。此外,fetch
是异步的,这意味着您尝试在网络请求完成之前记录 userId
。要解决这个问题,请将您的日志放在第二个 then
回调中并返回 fetch
:
findUserId() {
if (accessToken === undefined) {
this.getAccessToken();
}
console.log(accessToken);
return fetch(`https://api.spotify.com/v1/me`, {
headers: { Authentication: `Bearer ${accessToken}` }
})
.then(response => response.json())
.then(jsonResponse => {
userId = jsonResponse.id;
console.log(userId);
return userId;
});
}
然后你可以像这样使用findUserId
:
async otherFunction() {
const userId = await this.findUserId();
console.log(userId);
}
或者像这样:
otherFunction() {
this.findUserId().then(userId => console.log(userId));
}
关于javascript - 来自 API 提取的未处理的拒绝类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48603005/