问题描述
我正在运行以下js代码。但是我一直从Spotify网页中收到错误消息(说存在某种错误)。 credentials 是base64编码的client_id和secret字符串。
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);
});
解决方法
根据Spotify Authorization guide中的规定,正文必须为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);
});