[英]Unhandled Rejection Type Error from API fetch
在使用Spotify Web應用程序時出現一個奇怪的錯誤。 我嘗試將播放列表保存到我的帳戶,該帳戶必須從https://api.spotify.com/v1/me端點獲取id
元素,然后將播放列表應用於您的帳戶。 否則,一切似乎都很好,將其暫存到該端點,這將引發錯誤:
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
應該是一個對象-更改
{headers: `Bearer ${accessToken}`}
至
{headers: {'Authorization': `Bearer ${accessToken}`}}
首先,您必須在headers
設置Authentication
標headers
。 同樣, 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));
}
那不是您使用fetch進行標頭的方式。 我認為您的意思是設置授權標頭。 參見https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Headers
編輯:錯誤的鏈接
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.