在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
发布评论