Reactjs 如何在react中处理404

Reactjs 如何在react中处理404,reactjs,react-router,Reactjs,React Router,如何在React JS中处理错误的route 404响应并路由到默认根上下文 我试着使用,但它不起作用,而且路径错误 您需要使用react路由器 在您的情况下,如果您使用/进行路由,但未实现服务器端呈现,则必须为所有请求响应索引文件 router.all('*', (req, res) => { res.response('index'); } ) 然后在你的客户端路由中把这个重定向放在最后 <Redirect from="*" to="/" /> 如果您使用的是#

如何在React JS中处理错误的route 404响应并路由到默认根上下文


我试着使用
,但它不起作用,而且路径错误

您需要使用react路由器


在您的情况下,如果您使用
/

进行路由,但未实现服务器端呈现,则必须为所有请求响应索引文件

  router.all('*', (req, res) => { res.response('index'); } )
然后在你的客户端路由中把这个重定向放在最后

<Redirect from="*" to="/" />


如果您使用的是
#
不要关心服务器部分

我认为您应该提供更多的信息。到目前为止,你得到的答案都是你没有具体说明的假设。就我个人而言,我想知道index.html是什么,404是什么意思。服务器给你这个了吗?你的路线不匹配吗?您使用什么版本的react路由器?webpack开发服务器和/或开发中间件是否处于混合状态

我假设后者在这里扮演了一个角色,但是如果需要的话,在你详细说明之后,我会改变我的答案

如果使用webpack dev server,请确保配置文件中包含以下内容

    devServer: {
    historyApiFallback: true, <- falls back to index.html if path is not routed
    publicPath: '/', <- where the bundle is
}
devServer:{

historyApiFallback:是的,你能分享你的路由文件吗?你能分享更多关于这个的上下文吗?给定的信息不足以给出一个完整的答案。这是捕获v4的非匹配路由的新路由的最佳答案
output: {
    path: path.sesolve(__dirname, 'dist') <- absolute path where the bundle is
    publicPath: '/' <- makes sure HtmlWebpackPlugin injects '/' before bundle.js in output index.html
}
  <Switch>
    <Route exact path="/" component={Home}/>
    <Route exact path="/someroute" component={SomeComponent}/>
    <Route component={NoMatchedRouteComponent}/> <- Catches "404" and redirects
  </Switch>