Reputation: 323
I got a weird error while working on my Spotify Web Application. I try to save a playlist to my account, which has to fetch the id
element from the https://api.spotify.com/v1/me endpoint, then apply the playlist to your account. Everything seems fine otherwise, besided the fetch to that endpoint, which throws the error:
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>)'
I've never seen this error before, and am not sure why it's happening. The findUserId
method is:
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;
}
Upvotes: 5
Views: 14214
Reputation: 18546
First, you have to set the Authentication
header inside headers
. Also, fetch
is async, which means that you try to log userId
before the network request has finished. To fix that, put your log inside the second then
callback and return the 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;
});
}
Then you can use findUserId
like this:
async otherFunction() {
const userId = await this.findUserId();
console.log(userId);
}
or like this:
otherFunction() {
this.findUserId().then(userId => console.log(userId));
}
Upvotes: 3
Reputation: 502
headers
should be an object - change
{headers: `Bearer ${accessToken}`}
to
{headers: {'Authorization': `Bearer ${accessToken}`}}
Upvotes: 3
Reputation: 1398
That's not how you do headers with fetch. I think you mean to set the authorization header. See https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Headers
edit: wrong link
Upvotes: 1