Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled Rejection Type Error from API fetch

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;
}
like image 438
yourknightmares Avatar asked Feb 03 '18 23:02

yourknightmares


2 Answers

headers should be an object - change

{headers: `Bearer ${accessToken}`}

to

{headers: {'Authorization': `Bearer ${accessToken}`}}
like image 25
adamboro Avatar answered Sep 18 '22 20:09

adamboro


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));
}
like image 176
Fabian Schultz Avatar answered Sep 19 '22 20:09

Fabian Schultz