我已经尝试解决此问题了一个小时,但似乎无法解决。我正在使用node-fetch
来处理请求(这只是针对浏览器的Fetch API的副本,但已针对Node进行了克隆)。我有以下代码:
fetch("https://accounts.spotify.com/api/token", {
body: `grant_type=authorization_code&code=${req.query.code}&redirect_uri=${encodeURIComponent("http://localhost:3000/callback")}`,
headers: {
Authorization: `Basic ${btoa(my_client_id)}:${btoa(my_client_secret)}`,
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
})
这应该从回调中获取代码,并将其发送给Spotify以获取刷新令牌。
预期的行为:返回的应该是以下内容:
400错误请求(始终)
答案 0 :(得分:2)
这有效。看来您对凭据的编码不正确。
其base64({id}:{secret})
而非base64({id}):base64({secret})
。
我纯粹为了方便起见使用了request-promise
,因此,如果您在抓取中修复Authorization
标头,它应该可以工作。
const rp = require('request-promise');
const clientId = 'xxx';
const clientSecret = 'xxx';
async function auth() {
const credentialsBuffer = Buffer.from(`${clientId}:${clientSecret}`);
const options = {
method: 'POST',
uri: 'https://accounts.spotify.com/api/token',
form: {
grant_type: 'client_credentials'
},
headers: {
Authorization: `Basic ${credentialsBuffer.toString('base64')}`
},
};
const resp = await rp(options);
console.log(resp);
}
(async () => {
await auth();
})()