How to display page not found error page when an invalid API request is made in nodejs and reactjs app?

Viewed 13

I have not done this before I tried to see how it is done online but didn't see any reliable method. I keep seeing only the react.js part. I have a Middleware in node.js that returns route does not exist

const notFound = (req, res) => res.status(404).send('Route does not exist')

And I serve it this way in the app.js

app.use(notFoundMiddleware);


app.get('*', (req, res)=>{
res.sendFile(path.join(__dirname, 'build', 'index.html'));
})

This works in postman when I tested an invalid route. However, since I am serving my frontend below it, the code below it doesn't work. If I place the not found middleware below the frontend files, the frontend files would be served but the not found middleware won't work anymore.

How Am I supposed to serve not found middleware and serve it in frontend using react.js?

0 Answers
Related