
Sometimes we want to programmatically send a 404 response in our Express app.
In this article, we’ll look at how to programmatically send a 404 response in our Express app.
To programmatically send a 404 response in our Express app, we can use the res.sendStatus
or res.status
Methods.
For example, we can write:
const express = require('express')
const app = express()
const port = 3000app.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}`)
})
call sendStatus
with 404 in the *
Route that runs whenever a request is received from a URL that is not captured by any other route.
We can also write:
const express = require('express')
const app = express()
const port = 3000app.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}`)
})
call res.status
with 404 to send a 404 response.
Then we’ll call send
with 'Not Found'
to ship it with a body.
To programmatically send a 404 response in our Express app, we can use the res.sendStatus
or res.status
Methods.