To get Node Express.js to 404 only on missing routes, we can return a 404 response with a middleware.
For instance, we write
router.use((req, res, next) => {
next({
status: 404,
message: "Not Found",
});
});
router.use((err, req, res, next) => {
if (err.status === 404) {
return res.status(400).render("404");
}
if (err.status === 500) {
return res.status(500).render("500");
}
next();
});
at the bottom of our code to call next
to send the 404 status
to the last middleware.
Then we check the err.status
for the value and call res.status
to return the status we want.
And we call render
to render the response body.