如何使用 JavaScript POST 到 Spotify API 令牌端点?

问题描述 投票:0回答:1

我正在运行以下 js 代码。但我不断从 Spotify 网页收到错误(说存在某种错误)。 credentials是client_id和secret的base64编码字符串。

curl 命令工作得很好:

curl -X "POST" -H "Authorization: Basic *credentials*" -d grant_type=client_credentials https://accounts.spotify.com/api/token

js代码无法正常工作..

我想这很简单,但我的 js 不太好(抱歉!)。

fetch('https://accounts.spotify.com/api/token', {
    method: 'POST',
    headers: {'Authorization': 'Basic *credentials*'},
    body: 'grant_type=client_credentials'
    })
    .then(response => response.json())
    .then(data => {
        console.log(data);
    });

javascript node.js spotify node-fetch
1个回答
2
投票

按照 Spotify 授权指南中的规定,正文必须是

application/x-www-form-urlencoded
,因此只需添加此标头:

fetch('https://accounts.spotify.com/api/token', {
    method: 'POST',
    headers: {
        'Authorization': 'Basic *credentials*',
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
    },
    body: 'grant_type=client_credentials'
})
.then(response => response.json())
.then(data => {
    console.log(data);
});
© www.soinside.com 2019 - 2024. All rights reserved.