使用NextJS API路由实现Spotify授权流时出现CORS错误如何解决
问题解决方法
错误根本原因
你遇到的CORS错误是OAuth2授权码流程的正常限制:Spotify的授权端点本身不允许跨域AJAX请求,你用fetch调用/api/login接口时,后端返回302重定向到Spotify授权页,fetch会自动跟随重定向请求Spotify的资源,触发浏览器的CORS拦截规则。
你直接在地址栏访问/api/login能正常走流程,是因为整页跳转不属于跨域AJAX请求的限制范围,和fetch请求的场景有本质区别。
修复步骤
- 第一步:修改前端逻辑,不要用fetch调用登录接口,改为整页跳转至
/api/login - 第二步:统一
login.ts和callback.ts中的回调地址,避免Spotify报地址不匹配错误 - 第三步:修改
callback.ts的返回逻辑,拿到token后重定向回前端页面,不要直接返回JSON
核心代码修改
1. 前端Login.tsx修改
删除原有useLogin钩子中fetch调用逻辑,改为从URL参数读取token,登录按钮直接跳转至授权接口:
import { useEffect, useState } from "react"; import WebPlayback from '../components/WebPlayback'; const App = () => { const [token, setToken] = useState(''); useEffect(() => { // 页面加载时从URL参数获取token const urlParams = new URLSearchParams(window.location.search); const accessToken = urlParams.get('access_token'); if (accessToken) { setToken(accessToken); // 清理URL中的参数,避免刷新重复获取 window.history.replaceState({}, document.title, window.location.pathname); } }, []); return ( <> { token === '' ? <a href="/api/login">登录Spotify</a> : <WebPlayback token={token} /> } </> ) } export default App;
2. api/login.ts修改
将redirect_uri修改为和callback.ts中一致的地址:
const input = { response_type: "code", client_id: process.env.SPOTIFY_CLIENT_ID, scope, redirect_uri: "http://localhost:3000/api/callback", // 替换原有地址 state, } as Record<string, string>;
3. api/callback.ts修改
拿到Spotify返回的token后,重定向回前端页面,携带token参数:
fetch(spotifyURL, config as RequestInit) .then(response => response.json()) .then(data => { if (data.access_token) { res.redirect(`http://localhost:3000?access_token=${data.access_token}&refresh_token=${data.refresh_token}`); } else { res.redirect(`http://localhost:3000?error=auth_failed`); } })
内容的提问来源于stack exchange,提问作者humanbean
相关产品推荐
相关产品推荐

