To redirect 404 errors to a page in Express.js, we can add a route that accepts requests from all URLs that haven’t been handled by other routes.
For instance, we can write:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) =>{
res.send('hello world');
});
app.get('*', (req, res) => {
res.send('not found', 404);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
to add a route that handles all routes that aren’t the /
route with:
app.get('*', (req, res) => {
res.send('not found', 404);
});
The asterisk indicates that this route is a catch-all route that handles any requests from URLs not handled by other routes.
Therefore, when we go to /
, we see hello world
.
Otherwise, we see not found
.