To programmatically send a 404 response in our Express app, we can use the res.sendStatus
or res.status
methods.
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.sendStatus(404);
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
to call sendStatus
with 404 in the *
route, which is run whenever a request is received from a URL that isn’t picked up by any other route.
We can also write:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('hello world');
});
app.get('*', (req, res) => {
res.status(404).send('Not found');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
to call res.status
with 404 to send a 404 response.
Then we call send
with 'Not Found'
to send it with a body.