所以这是我在 javascript 中的第一个项目,也是第一个与任何类型的 API 相关的项目。目前,我的任务是从某人的 spotify 帐户中获取前 3 位艺术家的列表。
为此,我制作了一个带有按钮的简单 HTML 页面,并将所有功能放在我项目中的 2 个 js 文件中。
我已经按照文档中的指示使用 PKCE 实现了身份验证,但是,当涉及到从身份验证端点重定向回后需要从 URL 解析请求令牌的部分时,它似乎失败了。我已经看了一段时间的代码,看不出是什么问题导致了这个问题。感谢所有帮助,但请尝试以 JS 和 API 初学者能够理解的方式进行解释。谢谢。
//This is the function that connects the user to the authentication server
function authenticate(){
const clientId = 'f101df3a42484b9e9aa1d1aa34fa5770';
const redirectUri = 'http://127.0.0.1:5500/index.html';
let codeVerifier = generateRandomString(128);
generateCodeChallenge(codeVerifier).then(codeChallenge => {
let state = generateRandomString(16);
let scope = 'user-top-read';
localStorage.setItem('code-verifier', codeVerifier);
let args = new URLSearchParams({
response_type: 'code',
client_id: clientId,
scope: scope,
redirect_uri: redirectUri,
state: state,
code_challenge_method: 'S256',
code_challenge: codeChallenge
});
window.location = 'https://accounts.spotify.com/authorize?' + args;
});
};
//This is the code that triggers after user is redirected back to previous page to parse the new token and use it for the request for the top 3 artists
function redirectToken(){
const urlParams = new URLSearchParams(window.location.search);
let code = urlParams.get('code');
let codeVerifier = localStorage.getItem('code_verifier');
const redirectUri = 'http://127.0.0.1:5500/index.html';
const clientId = "f101df3a42484b9e9aa1d1aa34fa5770";
let body = new URLSearchParams({
grant_type: 'authorization_code',
code: code,
redirect_uri: redirectUri,
client_id: clientId,
code_verifier: codeVerifier
});
const response = fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: body
})
.then(response => {
if (!response.ok) {
throw new Error('HTTP status ' + response.status);
}
return response.json();
})
.then(data => {
localStorage.setItem('access-token', data.access_token);
})
.catch(error => {
console.error('Error:', error);
});
};
我已经尝试将 code_verifier 更改为全局变量,因为我认为将它保存到 localStorage 不足以让它在从不同的函数引用时工作,但这似乎没有改变任何东西,redirectToken 中的发布请求( ) 函数仍然返回 400.
Spotify 很可能反对提供 redirect_uri。
const redirectUri = 'http://127.0.0.1:5500/index.html';
根据我的经验,对于其他 OAuth2 提供商,而不是 Spotify,redirect_uri 必须与针对 client_id 注册的内容完全匹配 - http/s 部分、主机名、端口和(有时)路径。
作为诊断步骤,请尝试输入准确的 redirect_uri 并查看它是否超过 400。因为在此步骤中您实际上并未使用 redirect_uri,所以您发送的内容无关紧要。
不幸的是,我建议的额外日志记录是不够的,因为它没有显示 400 响应的主体,但它至少有一个我们可以解压的。将
!response.ok
逻辑更新为以下内容。这也是错误处理的改进。
if (!response.ok) {
console.error('error response', response);
response.json().then(json => {
console.error('error body json', json);
throw new Error('HTTP status ' + response.status + ': ' + json.error + ":" + json.error_description);
});
throw new Error('HTTP status ' + response.status);
}
请将记录的对象添加到问题中,并展开所有内容。