Search code examples
apiexpressrequesttokenspotify

Can't get access token from Spotify API


I'm trying to use the Request module to make a POST request to https://accounts.spotify.com/api/token in order to get an access token. I've registered the redirect URI with my Spotify dev account. This is my express /redirect route.

const Request = require('request');

module.exports = (req, res) => {
  const data = {
    grant_type: 'authorization_code',
    code: req.query.code,
    redirect_uri: 'http://localhost:3000/redirect',
    client_id: process.env.SPOTIFY_ID,
    client_secret: process.env.SPOTIFY_SECRET
  }

  const options = {
    method: 'POST',
    url: 'https://accounts.spotify.com/api/token',
    json: true,
    body: data
  }

  Request(options, (error, response, body) => {
    if (error) return console.log(error);
    res.end(body);
  });
};

Can anyone see what might be wrong here? All I get is a nondescript 'Oops! Something went wrong' error page every time.


Solution

  • The data parameters have to be passed as a form data:

    const options = {
      method: 'POST',
      url: 'https://accounts.spotify.com/api/token',
      json: true,
      form: data
    }