How to Send JSON Response in Express: Simple Guide
In Express, you send a JSON response using the
res.json() method inside a route handler. This method automatically sets the Content-Type header to application/json and sends the JavaScript object or array as a JSON string to the client.Syntax
The basic syntax to send a JSON response in Express is:
res: The response object provided by Express.json(): A method that converts a JavaScript object or array into JSON format and sends it.
javascript
res.json(object)
Example
This example shows a simple Express server with a route that sends a JSON response containing a greeting message and a status code.
javascript
import express from 'express'; const app = express(); const port = 3000; app.get('/greet', (req, res) => { res.json({ message: 'Hello, world!', status: 'success' }); }); app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); });
Output
{"message":"Hello, world!","status":"success"}
Common Pitfalls
Some common mistakes when sending JSON responses in Express include:
- Using
res.send()with an object but forgetting that it may not always set the correctContent-Typeheader. - Trying to send multiple responses in one request, which causes errors.
- Not ending the response properly, leading to hanging requests.
Always use res.json() for JSON data to ensure proper headers and formatting.
javascript
/* Wrong way: Using res.send without JSON header guarantee */ app.get('/wrong', (req, res) => { res.send({ error: false, data: 'Test' }); }); /* Right way: Using res.json to send JSON response */ app.get('/right', (req, res) => { res.json({ error: false, data: 'Test' }); });
Quick Reference
Tips for sending JSON responses in Express:
- Use
res.json()to send JSON data with correct headers. - Pass a JavaScript object or array to
res.json(). - Do not call
res.json()more than once per request. - Use
res.status(code).json()to set HTTP status codes with JSON.
Key Takeaways
Use res.json() to send JSON responses with proper headers in Express.
Pass a JavaScript object or array to res.json() for automatic JSON conversion.
Avoid sending multiple responses in one request to prevent errors.
Use res.status(code).json() to set HTTP status codes along with JSON data.