如何为React Router添加服务端路由?Azure部署刷新遇404报错
解决React Router部署Azure后刷新404及StaticRouter导入报错问题
问题分析
- 刷新404核心原因:Azure的Web服务器默认仅处理实际存在的文件请求,而React Router的客户端路由是在浏览器端解析的。刷新页面时,服务器找不到对应路径的物理文件,就会返回404。
- 你的代码问题:把服务端渲染(SSR)逻辑(比如
http.createServer、ReactDOMServer.renderToString、StaticRouter)直接写到了客户端组件里——客户端代码是要打包后在浏览器运行的,根本无法识别Node.js的http模块;同时react-router-dom/server的导出在客户端打包环境下存在兼容性问题,这就是你遇到的Action导出错误的根源。
正确解决方案(无需SSR)
情况1:使用Azure Static Web Apps部署
在项目根目录创建staticwebapp.config.json文件,添加路由重写规则,让所有请求都指向index.html:
{ "routes": [ { "route": "/*", "serve": "/index.html", "statusCode": 200 } ] }
打包React应用后重新部署到Azure Static Web Apps,刷新页面就不会再出现404。
情况2:使用Azure App Service部署(Node.js托管)
如果用Express托管静态文件,需要单独写一个Node.js服务文件(不要写到React组件里):
const express = require('express'); const path = require('path'); const app = express(); // 托管打包后的静态资源 app.use(express.static(path.join(__dirname, 'build'))); // 所有路由请求都返回index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'build', 'index.html')); }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
将打包后的build文件夹和这个服务文件一起部署到Azure App Service,配置启动命令为node server.js(假设服务文件名为server.js)。
修正后的React路由组件
删掉所有服务端相关代码,保留纯客户端路由即可:
import Navbar from './Components/Navbar' import FootBall from './Components/Football' import LiveMatches from './Components/LiveMatches' import Home from './Components/Home' import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; import './css/index.css'; function App() { return ( <div> <Router> <Navbar /> <Routes> <Route path="/" element={<Home/>}/> <Route path="/lega-serie-a" element={<FootBall/>}/> <Route path="/live-matches" element={<LiveMatches/>}/> </Routes> </Router> </div> ); } export default App;
内容的提问来源于stack exchange,提问作者Matteo Pagliarello
相关产品推荐
相关产品推荐

