Tia*_*ago 1 node.js express axios
在 Express 后端服务器上使用 axios 发出发布请求时,我试图从 Spotify API 检索访问令牌。到目前为止,我一直没有成功。我收到以下错误:
数据:{错误:'unsupported_grant_type',error_description:'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}!`));
Run Code Online (Sandbox Code Playgroud)
我希望能够在来自 Spotify API 的响应中检索访问令牌。请帮忙!
从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' }));
Run Code Online (Sandbox Code Playgroud)
所以,在你的情况下,你可以尝试 data: querystring.stringify({ grant_type: 'client_credentials' })
| 归档时间: |
|
| 查看次数: |
1813 次 |
| 最近记录: |