在Express.js上使用Axios向Spotify API发出POST请求时出现错误400

时间:2019-04-01 17:37:52

标签: node.js express axios

在Express后端服务器上使用axios发出发布请求时,我试图从Spotify API中检索访问令牌。到目前为止,我一直没有成功。我收到以下错误:

数据:       {错误:“ unsupported_grant_type”,         错误说明:          'grant_type必须是client_credentials,authorization_code或refresh_token'}}

我已经尝试将'grant_type'的'data'属性更改为'params',但仍然无法正常工作。任何建议都会有所帮助。

const express = require('express');
const axios = require('axios');
const dotenv = require('dotenv');
dotenv.config();
const app = express();
const port = 3000;

const client_id = process.env.CLIENT_ID;
const client_secret = process.env.CLIENT_SECRET;

app.get('/spotify-authorization', (req, res) => {
  axios({
    method: 'post',
    url: 'https://accounts.spotify.com/api/token',
    data: {
      grant_type: 'client_credentials'
    },
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization:
        'Basic ' +
        Buffer.from(client_id + ':' + client_secret).toString('base64')
    }
  })
    .then(response => {
      console.log(response.data);
    })
    .catch(error => {
      console.log(error);
    });

  res.send('successful response received!');
});

app.listen(port, () => console.log(`Express app listening on port ${port}!`));

我希望能够从Spotify API的响应中检索访问令牌。请帮忙!

2 个答案:

答案 0 :(得分:0)

来自axios文档:By default, axios serializes JavaScript objects to JSON. To send data in the application/x-www-form-urlencoded format instead, you can use one of the following options.

对于Nodejs,您可以按以下方式使用querystring模块:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

因此,在您的情况下,您可以尝试data: querystring.stringify({ grant_type: 'client_credentials' })

答案 1 :(得分:0)

由于声誉低下,我无法发表评论,但是1556089774的答案应该是被接受的答案。自从Spotify的iOS SDK指向https://glitch.com/~spotify-token-swap作为一个不起作用的示例以来,我花了4个小时多的时间研究它为什么不起作用。将stringify添加到请求的数据部分可以使其工作:

data: querystring.stringify ({
  grant_type: "authorization_code",
  redirect_uri: SPOTIFY_CLIENT_CALLBACK_URL,
  code: authorization_code
})
相关问题