JSON is a simple way to send and receive data between a client and a server. Express helps handle JSON easily in web apps.
JSON request and response patterns in Express
Start learning this pattern below
Jump into concepts and practice - no test required
app.use(express.json()) app.post('/path', (req, res) => { const data = req.body res.json({ message: 'Received', yourData: data }) })
Use express.json() middleware to parse incoming JSON requests automatically.
Use res.json() to send JSON responses easily.
app.use(express.json()) app.post('/user', (req, res) => { const user = req.body res.json({ status: 'success', user }) })
app.get('/info', (req, res) => { res.json({ app: 'MyApp', version: '1.0' }) })
This program creates a simple Express server that listens on port 3000. It uses JSON middleware to parse incoming JSON data. When a POST request is sent to /echo with JSON data, it responds by sending back a JSON object confirming receipt and showing the data.
import express from 'express' const app = express() const port = 3000 app.use(express.json()) app.post('/echo', (req, res) => { const receivedData = req.body res.json({ message: 'Data received', data: receivedData }) }) app.listen(port, () => { console.log(`Server running on http://localhost:${port}`) })
Always use express.json() before routes that expect JSON data.
Clients must set the Content-Type header to application/json when sending JSON.
Use res.json() instead of res.send() for automatic JSON formatting and headers.
Express makes handling JSON requests and responses simple with built-in middleware.
Use express.json() to parse incoming JSON data automatically.
Use res.json() to send JSON responses with correct headers.
Practice
express.json() middleware do in an Express app?Solution
Step 1: Understand middleware purpose
Theexpress.json()middleware is designed to parse JSON data sent in the request body.Step 2: Differentiate from response methods
Sending JSON responses is done byres.json(), notexpress.json().Final Answer:
It parses incoming JSON request bodies automatically. -> Option BQuick Check:
express.json() parses JSON requests [OK]
- Confusing express.json() with res.json()
- Thinking it sends JSON responses
- Assuming it validates JSON schema
Solution
Step 1: Identify Express response methods
Express providesres.json()to send JSON responses with proper headers.Step 2: Check method names
Methods likesendJsonorjsonifydo not exist in Express.Final Answer:
res.json({ message: 'Hello' }) -> Option CQuick Check:
Use res.json() to send JSON responses [OK]
- Using non-existent methods like sendJson or jsonify
- Using res.send() without JSON formatting
- Confusing method names
{ "name": "Alice" } is sent?app.use(express.json());
app.post('/greet', (req, res) => {
const user = req.body.name;
res.json({ greeting: `Hello, ${user}!` });
});Solution
Step 1: Parse JSON body with express.json()
The middleware parses the JSON body, soreq.body.nameis 'Alice'.Step 2: Construct JSON response
The response sends{ greeting: `Hello, Alice!` }as JSON.Final Answer:
{ "greeting": "Hello, Alice!" } -> Option DQuick Check:
Parsed JSON body used in res.json() response [OK]
- Forgetting to use express.json() middleware
- Accessing req.body before parsing
- Expecting undefined instead of 'Alice'
app.post('/data', (req, res) => {
const data = req.body;
res.json({ received: data });
});Solution
Step 1: Check JSON parsing middleware
The code accessesreq.bodybut does not showexpress.json()middleware usage.Step 2: Understand middleware necessity
Withoutexpress.json(),req.bodywill be undefined for JSON requests.Final Answer:
Missing express.json() middleware to parse JSON body. -> Option AQuick Check:
express.json() needed to parse JSON requests [OK]
- Assuming req.body is parsed automatically
- Confusing res.json() with res.send()
- Using wrong HTTP method for JSON POST
Solution
Step 1: Use express.json() middleware to parse JSON array
app.post('/sum', express.json(), (req, res) => { const numbers = req.body; const sum = numbers.reduce((a, b) => a + b, 0); res.json({ sum }); }); correctly usesexpress.json()middleware inline to parse the JSON array in the request body.Step 2: Sum array and send JSON response
It sums the numbers withreduceand sends the result withres.json(), which sets correct headers.Step 3: Identify errors in other options
app.post('/sum', (req, res) => { const numbers = JSON.parse(req.body); const sum = numbers.reduce((a, b) => a + b, 0); res.json({ sum }); }); tries to parsereq.bodymanually, 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 }); }); usesexpress.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 }); }); accessesreq.body.numbersbut expects array directly in body; also usesres.send()which may not set JSON headers properly.Final Answer:
app.post('/sum', express.json(), (req, res) => { const numbers = req.body; const sum = numbers.reduce((a, b) => a + b, 0); res.json({ sum }); }); -> Option AQuick Check:
express.json() + res.json() for JSON array sum [OK]
- Not using express.json() to parse JSON body
- Using express.urlencoded() for JSON data
- Manually parsing req.body with JSON.parse
- Using res.send() instead of res.json() for JSON response
