res.status sets the HTTP status code for the response. It tells the browser or client if the request was successful or if there was an error.
0
0
res.status for status codes in Express
Introduction
When you want to tell the client that a request was successful (like 200 OK).
When you want to indicate a resource was created (like 201 Created).
When you want to show an error happened (like 404 Not Found).
When you want to redirect the client (like 302 Found).
When you want to signal the client to try again later (like 503 Service Unavailable).
Syntax
Express
res.status(statusCode)
statusCode is a number like 200, 404, or 500.
You usually chain res.status() with res.send() or res.json() to send the response.
Examples
Sends a 200 OK status with a simple text message.
Express
res.status(200).send('OK')
Sends a 404 Not Found status with a message.
Express
res.status(404).send('Page not found')
Sends a 201 Created status with a JSON object.
Express
res.status(201).json({ id: 123 })
Sample Program
This Express app has three routes. Each route sends a different HTTP status code using res.status() and a message or JSON response.
Express
import express from 'express'; const app = express(); app.get('/success', (req, res) => { res.status(200).send('Request was successful'); }); app.get('/notfound', (req, res) => { res.status(404).send('Resource not found'); }); app.get('/created', (req, res) => { res.status(201).json({ message: 'New item created' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
OutputSuccess
Important Notes
Always set the status code before sending the response.
If you don't set a status code, Express defaults to 200.
Use correct status codes to help clients understand the result of their request.
Summary
res.status sets the HTTP status code for the response.
It helps communicate success, errors, or other states to the client.
Always chain it with res.send() or res.json() to send the response.