How to Send Status Code in Express: Simple Guide
In Express, you send a status code using the
res.status(code) method followed by res.send() or res.json(). For example, res.status(404).send('Not Found') sends a 404 status with a message.Syntax
The basic syntax to send a status code in Express is:
res.status(code): Sets the HTTP status code for the response.res.send(body): Sends the response body as a string or buffer.res.json(object): Sends a JSON response.
You chain res.status() with res.send() or res.json() to send both status and content.
javascript
res.status(200).send('OK')
Example
This example shows an Express server that sends different status codes based on the route:
javascript
import express from 'express'; const app = express(); app.get('/', (req, res) => { res.status(200).send('Hello, world!'); }); app.get('/notfound', (req, res) => { res.status(404).send('Page not found'); }); app.get('/error', (req, res) => { res.status(500).json({ error: 'Internal Server Error' }); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
Common mistakes when sending status codes in Express include:
- Calling
res.send()orres.json()without setting a status code, which defaults to 200. - Calling
res.status()afterres.send(), which has no effect because the response is already sent. - Forgetting to end the response, causing the request to hang.
Always chain res.status() before sending the response.
javascript
/* Wrong way: status set after sending response */ res.send('OK'); res.status(400); // This does nothing /* Right way: status set before sending response */ res.status(400).send('Bad Request');
Quick Reference
| Method | Description | Example |
|---|---|---|
| res.status(code) | Sets HTTP status code | res.status(404) |
| res.send(body) | Sends response body as string | res.send('OK') |
| res.json(object) | Sends JSON response | res.json({ error: 'Not found' }) |
| Chaining | Set status then send response | res.status(500).send('Error') |
Key Takeaways
Use res.status(code) before res.send() or res.json() to set HTTP status code.
Chaining res.status() with res.send() or res.json() sends both status and content.
Setting status after sending response has no effect and causes bugs.
Default status code is 200 if not explicitly set.
Always end the response to avoid hanging requests.