在Express.js上使用Axios向Spotify API发出POST请求时出现错误400 [英] Error 400 when making POST request to Spotify API with Axios on Express.js

查看:201
本文介绍了在Express.js上使用Axios向Spotify API发出POST请求时出现错误400的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to retrieve an access token from the Spotify API when making a post request with axios on an Express back end server. So far I have been unsuccessful. I'm getting the following error:

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

data: { error: 'unsupported_grant_type', error_description: 'grant_type must be client_credentials, authorization_code or refresh_token' } } }

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

I've already tried to change 'data' property for 'grant_type' to 'params' but it's still not working. Any advice would help.

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的响应中检索访问令牌.请帮忙!

I want to be able to retrieve the access token in the response from the Spotify API. Please help!

推荐答案

来自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 模块,如下所示:

For Nodejs you can use the querystring module as follows:

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

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

这篇关于在Express.js上使用Axios向Spotify API发出POST请求时出现错误400的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆