2

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?

4

1 回答 1

2

问题是我发布了一个表单并且在通过网络时没有对其进行编码并且我没有设置Content-Type. 我将我的更改authOptions为:

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
};

一切正常。

于 2015-12-05T22:32:17.410 回答