跨域问题解决:v6路由配置优化
在将项目从React Router v5升级到v6版本后,遇到了一个棘手的跨域问题。虽然路由配置看似正常,但在开发环境中访问特定路由时总是出现CORS错误。
问题现象
Access to fetch at 'http://localhost:3000/api/users' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
根本原因分析
经过排查发现,v6版本中路由配置的变更导致了开发服务器代理配置失效。在v5中我们使用了<BrowserRouter>配合basename属性,而v6取消了该属性,导致请求路径处理异常。
解决方案
- 修改proxy配置:在
package.json中添加或更新代理配置
"proxy": "http://localhost:3001"
- 调整路由配置:确保所有相对路径正确引用
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/users" element={<UserList />} />
<Route path="/profile" element={<Profile />} />
</Routes>
</BrowserRouter>
);
}
- 服务端配置:在后端API服务器添加CORS头
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
next();
});
验证步骤
- 启动开发服务器
- 访问
http://localhost:3000/users - 检查浏览器控制台无跨域错误
- 网络面板显示请求正常返回数据

讨论