Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return 404 status code when URL does not match at ReactJS

I use react router v4. So i am trying to return (IF it is possible) a status code 404 at the headers my code is here

export default class App extends Component {
  displayName = App.name

render() {
    return (
        <Layout>
            <Switch>
                <Route exact path='/' component={Home} />
                <Route path='/sitemap/:S' component={SiteMap} />
                <Route path='/videos' component={Videos} />
                <Route path='/contact' component={Contact} />
                <Route path='/privacy' component={Privacy} />
                {/*<Route path='/errorpage' component={Error404} status={404} />*/}
                <Route component={Error404}/>
            </Switch>
      </Layout>
    );
  }
}
like image 782
vkampouris Avatar asked Sep 05 '25 15:09

vkampouris


1 Answers

You handle well your 404 Not Found page but it is not possible to update headers in your client side.

To update headers you have to set it to your backend. If you use Express for example, you can write at the last level of your code

app.use((error, req, res, next) => {
    res.status(404).render('index');
    //OR
    res.status(404).sendFile('path/to/index.html') // Where index.html is your entry point
});
like image 96
mcssym Avatar answered Sep 08 '25 12:09

mcssym