reading data from Express Server after making Axios call in ReactJS, Spotify API

Viewed 21

My goal is to retrieve the data from the endpoint https://api.spotify.com/v1/me/top/tracks. I've setup an express server to handle routing and here is the endpoint.

app.get('/api/top/tracks', (req, res) => {

  axios({
    method: 'GET',
    url: 'https://api.spotify.com/v1/me/top/tracks',
    data: queryString.stringify({
      limit: 30,
      offset: 0,
      time_range: 'medium_term'
    }),
    headers: {
      'Authorization': 'Basic ' + encodedPayload,
      'Content-type': 'application/json',
    }
  }).then(response => {
    console.log(response.data)
    res.json(response.data)
 }).catch(error => console.log(error.response))
})

In another React functional component, I am trying to read the value in a useEffect, something like this.


  const [topTracks, setTopTracks] = useState(tracks)

  useEffect(() => {
    async function getTopTracks() {
      const response = await fetch('/api/top/tracks');
      const json = await response.json();
      setTopTracks(json);
    }

    getTopTracks();

  }, []);

In all honesty I think I just don't understand the Response Promise object from API calls and am not sure how to handle the data I am attempting to retrieve.

EDIT: Appended .catch to the end of axios call. But now I receive a very long error response for an HTTP error 400 Bad Request.

1 Answers

If you are pointing to your local express server, then your fetch call from your react component needs to point to the full url. Right now, your component's useEffect is unable to resolve to the correct endpoint, i.e. the express server

const response = await fetch('http://localhost:3000/api/top/tracks');

Note that depending on where your express server is hosted on, you might have to replace the localhost portion of the url

Related