我想使用提到的“客户端凭据流程”访问 Spotify Web API here 。我尝试使用一些教程提及 here 来访问它,但无法遵循它,因为它使用了节点中的请求库,该库现已被弃用,因此,我尝试在它的位置使用 axios 并不断在浏览器控制台中收到状态代码 415 错误。我正在尝试使用此 API 创建一个副项目进行练习,因为我是初学者。我已经使用 NodeJS 和普通浏览器控制台完成了此操作(我在这里使用了浏览器控制台的代码),并且安装了 axios 和express 库(在使用节点时)。
const client_id = '**redacted**';
const client_secret = '**redacted**';
const res = axios.post('https://accounts.spotify.com/api/token', {
headers: {
'Authorization': 'Basic ' + btoa(`${client_id}` + ':' + `${client_secret}`),
},
form: {
grant_type: 'client_credentials'
}
});
console.log(res)
<!DOCTYPE html>
<html lang="en">
<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 src="script2.js"></script>
</body>
</html>
最佳答案
Spotify 的 API 要求您在 application/x-www-form-urlencoded
中对 POST 请求正文进行编码。要使用 axios 执行此操作,您需要使用其他库或自行创建 serialize()
函数(我使用 serialize(obj)
函数 from this answer )。
<!DOCTYPE html>
<html lang="en">
<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>
另一个解决方案是简单地使用 request自动序列化数据的库。
此外,请注意使用客户端凭据授予类型发出请求。这样您就可以公开您的 client_secret
并为其他人提供模拟您的应用程序的方法。
客户端凭据授权类型只能在服务器端使用,这样您就可以确保您的 client_secret
不会被泄露。
如果您想在客户端对用户进行安全身份验证,请使用带有 PKCE 的授权代码(更好)或隐式授权类型。
关于javascript - 在 Spotify API 中授权期间获取 HTTP 415 不支持的媒体类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62682783/