如何处理404反应

Pra*_*ari 2 reactjs react-router

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

我尝试使用,<Route path='*' component={Home} />但它不起作用,并给出404错误的路径.

jar*_*m1r 7

我想你应该多给一些信息.到目前为止你得到的答案是你没有指定的假设.我想知道什么是index.html,你对404有什么意义.服务器给你这个吗?你的路线不匹配吗?你使用什么版本的react-router?混合使用webpack开发服务器和/或开发中间件吗?

我假设后者在这里扮演一个角色,但如果你需要指定更多,我会改变我的答案.

如果您使用webpack-dev-server,请确保以下内容位于您的配置文件中

    devServer: {
    historyApiFallback: true, <- falls back to index.html if path is not routed
    publicPath: '/', <- where the bundle is
}
Run Code Online (Sandbox Code Playgroud)

确保在webpack配置中您的输出具有publicPath

output: {
    path: path.sesolve(__dirname, 'dist') <- absolute path where the bundle is
    publicPath: '/' <- makes sure HtmlWebpackPlugin injects '/' before bundle.js in output index.html
}
Run Code Online (Sandbox Code Playgroud)

如果您不使用HtmlWebpackPlugin,请确保您的index.html引用'/bundle.js'不仅仅是捆绑.

如果您在节点中使用Webpack-dev-middleware来为索引和bundle提供服务,请注意它从内存而不是任何/ build或/ dist目录服务它.

如果问题出在react-router我不明白404问题.你的意思是它不匹配任何你的路线?如果您使用react-router v4,请确保您拥有最新的测试版,最新版本(4.0.0-beta.6)与之前的版本之间会有一些更改可能会破坏您期望的功能.

在路由器v4中使用它来捕获不匹配的路由:

  <Switch>
    <Route exact path="/" component={Home}/>
    <Route exact path="/someroute" component={SomeComponent}/>
    <Route component={NoMatchedRouteComponent}/> <- Catches "404" and redirects
  </Switch>
Run Code Online (Sandbox Code Playgroud)

也许console.log(this.props.match)在你的组件中看到你的路由发生了什么..

希望这有所帮助,请提供更多详细信息,以便我们为您提供更好的帮助..

  • 这是捕获v4针对非匹配路由的新路由的最佳答案 (2认同)