Beginner LevelExpress JS
What is the difference between res.json() and res.send() when returning objects?
❓ Interview Prompt: Compare res.json() vs res.send() regarding Content-Type header setting and object JSON serialization.
Both 'res.json()' and 'res.send()' send HTTP responses to the client, but handle data types differently:
1. 'res.json(obj)':
•
Explicitly formats data as JSON.
•
Sets 'Content-Type: application/json; charset=utf-8' header automatically.
•
Serializes objects, arrays, numbers, and booleans using 'JSON.stringify()'.
2. 'res.send(body)':
•
Inspects the argument type dynamically:
•
If given a Buffer, sets 'Content-Type: application/octet-stream'.
•
If given a String, sets 'Content-Type: text/html'.
•
If given an Object or Array, delegates internally to 'res.json()'.
Best Practice:
Always use 'res.json()' explicitly when returning API payloads for clarity and consistency.
Code Implementation Example
javascript
import express from 'express';
const app = express();
// 1. res.json explicitly sets application/json and serializes payload
app.get('/api/json', (req, res) => {
res.json({ message: 'Explicit JSON payload', success: true });
});
// 2. res.send sets text/html for string payloads
app.get('/api/html', (req, res) => {
res.send('<h1>HTML String Content</h1>');
});💡Comparing explicit res.json API payload responses vs res.send HTML responses.
🎯 Interview Key Takeaway
Use res.json() explicitly for REST API JSON responses to guarantee application/json headers and stringification.
#res.json#res.send#Responses#Beginner
Back to all Express JS Questions→