2015-12-04 7 views
2

У меня есть небольшое приложение Spotify, которое я пытаюсь преобразовать, чтобы использовать библиотеку http. У меня возникла проблема с обратным вызовом при входе в систему. До этого момента я использовал request, как и во всей документации Spotify. Все отлично работает с request, но, несмотря на то, что все выглядит одинаково с axios, я получаю 500 Internal Server Error. Вот мой код, чтобы сделать http запрос:Почему мой callback не работает с библиотекой axios?

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. Что еще мне не хватает?

ответ

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

и все работало нормально.