Return a not-found response
A route cannot find the requested resource and needs to return the conventional 404 status text.
Express.js · Module
res.sendStatus(statusCode) sets an HTTP status and sends its registered status message as a text response. For an unknown code, the body is the numeric code itself.
Call this response method with an HTTP status number to set the response status and immediately send its registered status message as plain text. If the number is not recognized, Express sends the numeric code as the body instead; the method returns the response object for chaining or inspection.
res.sendStatus(statusCode)| Name | Type | Description |
|---|---|---|
statusCode | Number | HTTP status code to set; its registered status message becomes the response body. |
Response
const express = require('express');
const app = express();
app.get('/missing', (req, res) => {
res.sendStatus(404);
});
app.listen(3000);Run the server and request /missing to receive a 404 response whose text body is the registered status message.
A route cannot find the requested resource and needs to return the conventional 404 status text.
A health, readiness, or validation endpoint needs only a status and standard text message.
A route must reject a request without constructing a custom body.
It accepts one numeric status code, sets that code on the response, and sends the corresponding registered status message as text. It returns the Response object.
Follow-up: What happens for an unrecognized code? Express sends the code number as the response body rather than a registered message.
Use res.sendStatus() when the response consists of a status and its standard text message. Use res.status().send() when the body must be custom or contain structured data.
Follow-up: How would you return a JSON error? Set the status separately, then call res.json() with the error object.
The argument is a Number representing the HTTP status code to set. The method returns Response, so the returned object is the Express response.
Follow-up: What should callers do if they need a different content type or message? Use res.status(statusCode) followed by an appropriate sending method.
res.status()res.send()res.json()