jhamm jhamm - 7 months ago 14
Javascript Question

Why is my callback not working with the axios library?

I have a small Spotify app that I am trying to convert to use the

axios
http
library. I am having an issue with the callback when logging in. Up to this point I have been using
request
like is in all of the
Spotify
documentation. Everything works fine with
request
, but even though everything looks the same with
axios
, I get a
500 Internal Server Error
. Here is my code to make the
http
request:

var authOptions = {
method: 'POST',
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64'))
},
json: true
};

axios(authOptions).then(res => {
console.log(res)
})


I can pass the same
authOptions
object to the
request
library everything works fine. Here is my request from
axios
logged out to the console.

{
method: 'POST',
url: 'https://accounts.spotify.com/api/token',
form:
{ code: 'changedthecode',
redirect_uri: 'http://localhost:8888/callback',
grant_type: 'authorization_code' },
headers: { Authorization: 'Basic changedthecode=' },
json: true,
timeout: 0,
transformRequest: [ [Function] ],
transformResponse: [ [Function] ],
withCredentials: undefined
}


And here is my response with the
axios
library:

{ data: { error: 'server_error' },
status: 500,
statusText: 'Internal Server Error',
headers:
{ server: 'nginx',
date: 'Fri, 04 Dec 2015 14:48:06 GMT',
'content-type': 'application/json',
'content-length': '24',
connection: 'close' },
config:
{ method: 'POST',
headers: { Authorization: 'Basic changedthecode' },
timeout: 0,
transformRequest: [ [Function] ],
transformResponse: [ [Function] ],
url: 'https://accounts.spotify.com/api/token',
form:
{ code: 'changedthecode',
redirect_uri: 'http://localhost:8888/callback',
grant_type: 'authorization_code' },
json: true,
withCredentials: undefined }
}


The only option that I didn't know about from
axios
was
withCredentials
, and it didn't work when it was set to
false
or
true
. What else am I missing?

Answer

The problem is that I was posting a form and was not encoding it when going across the wire and I was not setting the Content-Type. I changed my authOptions to:

var authOptions = {
    method: 'POST',
    url: 'https://accounts.spotify.com/api/token',
    data: querystring.stringify({
            grant_type: 'refresh_token',
            refresh_token: refreshToken
        }),
    headers: {
        'Authorization': 'Basic ' + (new Buffer(CLIENT_ID + ':' + CLIENT_SECRET).toString('base64')),
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    json: true
};

and everything worked fine.