Performance: JSON request and response patterns
This concept affects how quickly the server processes incoming data and sends responses, impacting server response time and perceived page load speed.
Jump into concepts and practice - no test required
const express = require('express'); const app = express(); app.use(express.json()); app.post('/data', (req, res) => { const data = req.body; // process data res.json({ status: 'ok' }); });
const express = require('express'); const app = express(); app.post('/data', (req, res) => { let body = ''; req.on('data', chunk => { body += chunk; }); req.on('end', () => { const data = JSON.parse(body); // process data res.setHeader('Content-Type', 'application/json'); res.end(JSON.stringify({ status: 'ok' })); }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual JSON parsing and response | N/A (server-side) | N/A | N/A | [X] Bad |
| express.json() middleware and res.json() | N/A (server-side) | N/A | N/A | [OK] Good |
express.json() middleware do in an Express app?express.json() middleware is designed to parse JSON data sent in the request body.res.json(), not express.json().res.json() to send JSON responses with proper headers.sendJson or jsonify do not exist in Express.{ "name": "Alice" } is sent?app.use(express.json());
app.post('/greet', (req, res) => {
const user = req.body.name;
res.json({ greeting: `Hello, ${user}!` });
});req.body.name is 'Alice'.{ greeting: `Hello, Alice!` } as JSON.app.post('/data', (req, res) => {
const data = req.body;
res.json({ received: data });
});req.body but does not show express.json() middleware usage.express.json(), req.body will be undefined for JSON requests.express.json() middleware inline to parse the JSON array in the request body.reduce and sends the result with res.json(), which sets correct headers.req.body manually, which is already parsed by middleware. app.post('/sum', express.urlencoded(), (req, res) => {
const numbers = req.body;
const sum = numbers.reduce((a, b) => a + b, 0);
res.json({ sum });
}); uses express.urlencoded() which is for form data, not JSON. app.post('/sum', (req, res) => {
const numbers = req.body.numbers;
const sum = numbers.reduce((a, b) => a + b, 0);
res.send({ sum });
}); accesses req.body.numbers but expects array directly in body; also uses res.send() which may not set JSON headers properly.