Tuesday, 9 May 2017

Spotify API - Getting 400 Response When Using Variable in Request Options

I am using the Spotify API and getting 400 responses to my requests. Specifically, I am using the Spotify "client credentials" flow, described here. I have isolated the issue below, with my credentials changed. Notice that the only difference between what is working and what isn't is that I am using a string vs a variable that is set to equal the string.

This does not work:

var authOptions = {
  url: 'https://accounts.spotify.com/api/token',
  headers: {
    'Authorization': 'Basic ' + (new Buffer(spotify.clientId + ':' + 
    spotify.clientSecret).toString('base64'))
  },
  form: {
    grant_type: 'client_credentials'
  },
  json: true
};

But this does work:

var authOptions = {
  url: 'https://accounts.spotify.com/api/token',
  headers: {
    'Authorization': 'Basic ' + (new Buffer('myClientIdHere' + ':' + 
    'myClientSecretHere').toString('base64'))
  },
  form: {
    grant_type: 'client_credentials'
  },
  json: true
};

My credentials.js file:

module.exports = {
    //...
    spotifyClientId: process.env.spotifyClientId,
    spotifyClientSecret: process.env.spotifyClientSecret,    
    //...       
}

And in app.js, before the authOptions variable:

var spotify = {
    clientId: credentials.spotifyClientId,
    clientSecret: credentials.spotifyClientSecret
};
console.log(spotify.clientId); // returns 'myClientIdHere'
console.log(spotify.clientSecret); // returns 'myClientSecretHere'

Thanks in advance for any advice.



via Jake 1986

No comments:

Post a Comment