You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React应用中重定向后如何获取Spotify API授权码?

解决Spotify认证中requestAccessToken提前执行的问题

问题本质

你当前的代码逻辑有个核心错误:当执行window.location = url后,浏览器会立即开始跳转到Spotify认证页面,当前页面的JavaScript代码会被终止执行。所以你写在window.location后面的requestAccessToken()要么根本不会运行,要么在旧页面(还没跳转)执行——这时候URL里自然没有Spotify返回的code,导致请求失败。

正确解决方案

把requestAccessToken()的调用从initiateLogin中移除,改成在重定向后的页面加载时自动检查URL中的code并执行请求。同时优化code的解析逻辑,避免无code时的错误。

1. 修改initiateLogin函数

移除多余的requestAccessToken()调用,只保留跳转逻辑:

export const initiateLogin = () => {
  const url = `https://accounts.spotify.com/authorize?response_type=code&client_id=${client_id}&scope=${encodeURIComponent(
    scopes.join(" ")
  )}&redirect_uri=${encodeURIComponent(redirect_uri)}`;

  window.location = url; // 跳转后当前页面脚本直接终止
};

2. 优化requestAccessToken函数

用URLSearchParams可靠解析查询参数,并增加code存在性检查:

const requestAccessToken = async () => {
  // 正确解析URL中的查询参数
  const urlParams = new URLSearchParams(window.location.search);
  const code = urlParams.get('code');

  // 如果没有code,直接返回,避免后续错误
  if (!code) {
    console.log("URL中不存在Spotify认证code");
    return;
  }

  console.log(code);
  const body = new URLSearchParams({
    grant_type: "authorization_code",
    code: code,
    redirect_uri: redirect_uri,
    client_id: client_id,
    client_secret: client_secret,
  });
  
  try {
    const response = await fetch("https://accounts.spotify.com/api/token", {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body,
    });

    if (response.ok) {
      const resp = await response.json();
      const { access_token, refresh_token, expires_in } = resp;
      localStorage.setItem("token", access_token);
      // 可选:获取令牌后跳转到应用首页
      // window.location = "/";
    } else {
      const errorDetails = await response.json();
      console.error("获取访问令牌失败:", errorDetails);
    }
  } catch (err) {
    console.error("请求过程出错:", err);
  }
};

3. 在React应用中自动触发token请求

在应用的根组件(比如App.js)中,使用useEffect在页面加载时自动检查并调用requestAccessToken:

import { requestAccessToken } from './authorization';
import { useEffect } from 'react';

function App() {
  useEffect(() => {
    // 页面挂载时自动检查URL中的code并请求令牌
    requestAccessToken();
  }, []);

  // 你的组件渲染逻辑...
  return (
    <div className="App">
      {/* 组件内容 */}
    </div>
  );
}

export default App;

流程说明

  1. 用户点击登录按钮,调用initiateLogin跳转到Spotify认证页面
  2. 用户完成授权后,Spotify会跳转到你配置的redirect_uri,此时URL中携带code参数
  3. 你的React应用加载该页面时,useEffect触发requestAccessToken,解析code并换取访问令牌

内容的提问来源于stack exchange,提问作者Ryan Slattery

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:24:56