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

编程入门 行业动态 更新时间:2024-10-27 17:09:30
本文介绍了在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: 'accounts.spotify/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('something/', querystring.stringify({ foo: 'bar' }));

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

更多推荐

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

本文发布于:2023-10-09 18:54:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1476498.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:出现错误   Axios   js   Express   Spotify

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!