How to Send Response in Express: Simple Guide
In Express, you send a response to the client using the
res object methods like res.send() for text or HTML, and res.json() for JSON data. These methods end the response and send data back to the browser or client.Syntax
Express response methods use the res object passed to your route handler. Common methods include:
res.send(body): Sends a response body as string, buffer, or object.res.json(object): Sends a JSON response with correct headers.res.status(code): Sets HTTP status code before sending response.
These methods end the response automatically.
javascript
app.get('/path', (req, res) => { res.status(200).send('Hello World'); });
Example
This example shows a simple Express server sending different types of responses: plain text, JSON, and setting status codes.
javascript
import express from 'express'; const app = express(); const port = 3000; app.get('/text', (req, res) => { res.send('Hello from Express!'); }); app.get('/json', (req, res) => { res.json({ message: 'Hello JSON' }); }); app.get('/status', (req, res) => { res.status(404).send('Not Found'); }); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
Output
Server running on http://localhost:3000
When visiting /text: Displays 'Hello from Express!'
When visiting /json: Displays JSON {"message":"Hello JSON"}
When visiting /status: Displays 'Not Found' with 404 status
Common Pitfalls
Common mistakes when sending responses in Express include:
- Calling
res.send()orres.json()multiple times in one request, which causes errors. - Not ending the response, leading to the client waiting indefinitely.
- Forgetting to set status codes when needed.
Always ensure only one response method is called per request.
javascript
app.get('/wrong', (req, res) => { // Wrong: sending twice res.send('First response'); res.send('Second response'); // This will cause an error }); app.get('/right', (req, res) => { res.status(200).send('Only one response'); });
Quick Reference
| Method | Purpose | Example |
|---|---|---|
| res.send(body) | Send string, buffer, or object as response | res.send('Hello') |
| res.json(object) | Send JSON response with headers | res.json({ key: 'value' }) |
| res.status(code) | Set HTTP status code | res.status(404).send('Not Found') |
| res.end() | End response without data | res.end() |
Key Takeaways
Use res.send() or res.json() to send responses and end them automatically.
Set HTTP status codes with res.status() before sending the response.
Never call multiple response methods in the same request handler.
res.json() automatically sets the Content-Type to application/json.
Always ensure your response ends to avoid hanging requests.