嗨,我正在尝试通过创建一个显示用户顶级 Spotify 统计数据的 Web 应用程序来学习开发,因此我尝试使用 supabase 登录 Spotify,但是重定向给出了以下形式的 URL:
http://127.0.0.1:8000/callback/#access_token=
我目前正在使用 Django,因为数据位于 URL 片段中,所以我无法使用 request.get 访问它。我将如何从 URL 中提取数据。
要从 Django 中的 URL 片段(也称为哈希片段)提取数据,您可以在前端代码中使用 JavaScript 来解析该片段,并将提取的数据发送到 Django 后端。以下是实现此目标的步骤:
更新您的 Spotify OAuth 重定向 URI: 确保您已将 Spotify OAuth 重定向 URI 设置为指向 Django 应用程序中的特定路由,例如:http://localhost:8000/callback/。
创建一个 JavaScript 函数以从 URL 片段中提取数据: 在 HTML 模板或 JavaScript 文件中,您可以创建一个函数来读取 URL 片段并提取必要的数据。这是一个使用 JavaScript 的示例:
function extractDataFromFragment() {
const fragment = window.location.hash.substring(1); // Remove the '#' character
const params = new URLSearchParams(fragment);
const accessToken = params.get('access_token');
// You can extract more data if needed (e.g., expiration time)
// Send the extracted data to your Django backend
fetch('/your-django-callback-endpoint/', {
method: 'POST',
body: JSON.stringify({ access_token: accessToken }),
headers: {
'Content-Type': 'application/json',
},
})
.then((response) => {
// Handle the response from the backend
// You can redirect the user or perform other actions here
})
.catch((error) => {
console.error(error);
});
}
配置您的 URL: 确保配置您的 Django URL 以将回调端点映射到您在步骤 4 中创建的视图。
通过这些步骤,您应该能够从 URL 片段中提取数据并将其发送到 Django 后端进行进一步处理。