为什么我的回调不能与axios库一起使用?

时间:2015-12-04 14:58:30

标签: javascript axios

我有一个小型Spotify应用,我尝试将其转换为使用axios http库。登录时我遇到了回调问题。到目前为止,我一直在使用request,就像所有Spotify文档一样。使用request一切正常,但即使axios的所有内容都相同,我也会获得500 Internal Server Error。以下是我提出http请求的代码:

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

我可以将相同的authOptions对象传递给request库,一切正常。以下是我axios登出控制台的请求。

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

以下是我对axios库的回复:

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

axios我唯一不知道的选项是withCredentials,当它设置为falsetrue时,它无效。我还缺少什么?

1 个答案:

答案 0 :(得分:3)

问题是我发布了一个表单,并且在通过电汇时没有对其进行编码,而我没有设置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
};

一切正常。