2 回答

TA貢獻1796條經(jīng)驗 獲得超7個贊
Spotify 的 API 要求您將 POST 請求的正文編碼為application/x-www-form-urlencoded
. 要使用 axios 執(zhí)行此操作,您需要使用其他庫或serialize()
自己制作函數(shù)(我使用了此答案serialize(obj)
中的函數(shù))。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AXIOS DOC</title>
</head>
<body>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const client_id = '**redacted**';
const client_secret = '**redacted**';
const serialize = function(obj) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
}
axios
.post('https://accounts.spotify.com/api/token',
serialize({
grant_type: 'client_credentials'
}), {
headers: {
'Authorization': 'Basic ' + btoa(client_id + ':' + client_secret),
}
})
.then(res => console.log(res.data.access_token))
.catch(err => {
console.log(err);
});
</script>
</body>
</html>
另一種解決方案是簡單地使用自動序列化數(shù)據(jù)的請求庫。
此外,請注意使用客戶端憑據(jù)授權類型發(fā)出請求。通過這種方式,您可以公開您client_secret的應用程序并讓其他人可以模擬您的應用程序。
客戶端憑據(jù)授予類型應僅在服務器端使用,您可以確保您client_secret不會被暴露。
如果您想在客戶端安全地對用戶進行身份驗證,請使用帶有 PKCE(更好)或隱式授權類型的授權代碼。

TA貢獻1876條經(jīng)驗 獲得超6個贊
我偶然發(fā)現(xiàn)了一個最近使用 axios 發(fā)出 POST 請求而不是請求庫的代碼片段。我剛剛嘗試過,并且能夠收到訪問令牌!如果您有任何問題,請告訴我。這是鏈接。一定要安裝 qs 包。
代碼看起來像這樣:
// Headers object.
const headers = {
headers: {
Accept: 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
},
auth: {
username: client_id,
password: client_secret,
},
};
// Data object.
const data = {
grant_type: 'client_credentials',
};
// Make the request using the URL, query string, data, and headers.
const res = axios.post('https://accounts.spotify.com/api/token', qs.stringify(data), headers);
// Retrieve the access token from the response.
const access_token = res.data.access_token;
添加回答
舉報