Node.js如何处理无效路由?配置后React访问无效路径空白需跳转首页
解决步骤
1. 补全前端路由配置
你当前仅在Switch中配置了首页路由,其余导入的登录、注册、列表等业务路由均未添加,所有非首页路径都会直接命中通配符路由,这是出现空白页的核心原因,请先将业务路由补全在首页路由和通配符路由之间:
import { Route, Switch, Redirect } from "react-router-dom"; // 新增导入Redirect组件 function App() { return ( <div className="app"> <Navbar/> <Switch> <Route exact path="/" component={Home}/> {/* 补全业务路由 */} <Route path="/register" component={Register}/> <Route path="/signin" component={Signin}/> <Route path="/forgot-password" component={ForgotPassword}/> <Route path="/reset-password" component={ResetPassword}/> <Route path="/update-password" component={UpdatePassword}/> <Route exact path="/list" component={List}/> <Route path="/list/:id" component={Details}/> {/* 通配符路由放在最后 */} <Route path="*"> <Redirect to="/" /> </Route> </Switch> </div> ); }
上述配置会直接将所有无效路径重定向到首页,无需渲染NotFound组件。
2. 可选:保留NotFound提示后跳转
如果需要先展示404提示再自动跳转首页,保留原来的NotFound路由配置,在NotFound组件中添加跳转逻辑即可:
// NotFound组件代码 import { useEffect } from 'react' import { useHistory } from 'react-router-dom' export default function NotFound() { const history = useHistory() useEffect(() => { // 不需要延迟可直接调用history.push('/') const timer = setTimeout(() => history.push('/'), 3000) return () => clearTimeout(timer) }, [history]) return <div>页面不存在,3秒后返回首页</div> }
服务端配置说明
你当前的Express配置已经满足前端路由的使用要求,所有非API请求都会返回React的index.html,无需修改。
内容的提问来源于stack exchange,提问作者Ashutosh Saini
相关产品推荐
相关产品推荐

