【问题标题】:Why is my callback not working with the axios library?为什么我的回调不能与 axios 库一起使用?
【发布时间】:2016-03-09 13:15:14
【问题描述】:

我有一个小型 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,当它设置为false 或true 时它不起作用。我还缺少什么?

【问题讨论】:

    标签: javascript axios


    【解决方案1】:

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

    一切正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-30
      • 2013-08-15
      • 1970-01-01
      • 2011-12-25
      • 2020-10-08
      • 2023-03-24
      • 1970-01-01
      相关资源
      最近更新 更多