Reputation: 79
How to handle incorrect route 404 response in React JS and route to default root context.
I tried to use <Route path='*' component={Home} />
but it's not working and for incorrect path giving 404.
Upvotes: 3
Views: 9046
Reputation: 775
I think you should give a little bit more information. The answers you got so far made assumptions you didn't specify. I for one would like to know what is serving the index.html and what do you mean with 404. Is the server giving you this? Are your routes not matching? What version of react-router do you use? Is webpack dev server and/or dev middleware in the mix?
I'm assuming the latter is playing a role here but will change my answer if needed after you specify more..
If you use webpack-dev-server make sure the follwing is in your config file
devServer: {
historyApiFallback: true, <- falls back to index.html if path is not routed
publicPath: '/', <- where the bundle is
}
Make sure in the webpack config your output has 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
}
If your not using HtmlWebpackPlugin then make sure your index.html references to '/bundle.js' not just bundle.
If your using Webpack-dev-middleware in node to serve the index and bundle, be aware it serves it from memory not any /build or /dist dir.
If the problem is with react-router I don't understand the 404 issue. You mean it is not matching against any of your routes? If you use react-router v4 make sure you have the latest beta, there are some changes between the latest (4.0.0-beta.6) and the one before that might break functionality you expect.
In router v4 use this to catch non matched routes:
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/someroute" component={SomeComponent}/>
<Route component={NoMatchedRouteComponent}/> <- Catches "404" and redirects
</Switch>
Maybe console.log(this.props.match)
in your component to see whats happening with your routing..
Hope this helped and please provide some more details so we can help you better..
Upvotes: 8
Reputation: 398
If you are using /
for routing but not implementing server side rendering then you must response index file for all requests.
router.all('*', (req, res) => { res.response('index'); } )
and then in your client routes put this redirect last
<Redirect from="*" to="/" />
If you are using #
don't care about the server part
Upvotes: 0