2 回答

TA贡献1796条经验 获得超7个赞
Spotify 的 API 要求您将 POST 请求的正文编码为application/x-www-form-urlencoded
. 要使用 axios 执行此操作,您需要使用其他库或serialize()
自己制作函数(我使用了此答案serialize(obj)
中的函数)。
<!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>
另一种解决方案是简单地使用自动序列化数据的请求库。
此外,请注意使用客户端凭据授权类型发出请求。通过这种方式,您可以公开您client_secret的应用程序并让其他人可以模拟您的应用程序。
客户端凭据授予类型应仅在服务器端使用,您可以确保您client_secret不会被暴露。
如果您想在客户端安全地对用户进行身份验证,请使用带有 PKCE(更好)或隐式授权类型的授权代码。

TA贡献1876条经验 获得超6个赞
我偶然发现了一个最近使用 axios 发出 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;
添加回答
举报