Bird
Raised Fist0
Expressframework~10 mins

JSON request and response patterns in Express - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - JSON request and response patterns
Client sends JSON request
Express server receives request
Parse JSON body middleware
Route handler processes data
Create JSON response object
Send JSON response to client
Client receives JSON
This flow shows how an Express server receives a JSON request, processes it, and sends back a JSON response.
Execution Sample
Express
app.use(express.json());

app.post('/data', (req, res) => {
  const name = req.body.name;
  res.json({ greeting: `Hello, ${name}!` });
});
This code receives a JSON request with a name, then responds with a JSON greeting.
Execution Table
StepActionInput/StateOutput/State Change
1Client sends POST /data with JSON body {"name":"Alice"}Request body: {"name":"Alice"}Request received by server
2express.json() middleware parses JSONRaw request bodyreq.body = { name: "Alice" }
3Route handler reads req.body.namereq.body = { name: "Alice" }name = "Alice"
4Route handler creates response JSONname = "Alice"Response body = { greeting: "Hello, Alice!" }
5Server sends JSON responseResponse bodyClient receives JSON { greeting: "Hello, Alice!" }
6Execution endsResponse sentConnection handled successfully
💡 Request handled and response sent, no further action
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
req.bodyundefined{"name":"Alice"}{"name":"Alice"}{"name":"Alice"}{"name":"Alice"}
nameundefinedundefined"Alice""Alice""Alice"
response JSONundefinedundefinedundefined{"greeting":"Hello, Alice!"}{"greeting":"Hello, Alice!"}
Key Moments - 2 Insights
Why do we need express.json() middleware before accessing req.body?
Because without express.json(), req.body is undefined. The middleware parses the raw JSON string into a JavaScript object, as shown in step 2 of the execution_table.
What happens if the client sends invalid JSON?
express.json() middleware will return an error and the route handler won't run. This prevents the server from crashing and ensures only valid JSON is processed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the value of 'name'?
Aundefined
B"Alice"
Cnull
D"name"
💡 Hint
Check the 'Input/State' and 'Output/State Change' columns at step 3 in execution_table
At which step does req.body get its parsed JSON object?
AStep 2
BStep 4
CStep 1
DStep 5
💡 Hint
Look for when express.json() middleware runs in execution_table
If the client sends {"name":"Bob"} instead, what changes in variable_tracker?
AOnly name changes to Bob
BNo changes, still Alice
Creq.body and name change to Bob
Dresponse JSON becomes empty
💡 Hint
See how req.body and name are assigned in variable_tracker after Step 3
Concept Snapshot
Express JSON request and response pattern:
- Use app.use(express.json()) to parse JSON body
- Access data via req.body in route handlers
- Send JSON response with res.json({key: value})
- Handles JSON automatically both ways
- Ensures client-server data exchange in JSON format
Full Transcript
This visual execution shows how an Express server handles JSON requests and responses. First, the client sends a POST request with a JSON body containing a name. The express.json() middleware parses this raw JSON string into a JavaScript object and assigns it to req.body. The route handler then reads the name property from req.body and creates a greeting message. Finally, the server sends this greeting back as a JSON response using res.json(). The variable tracker shows how req.body and name change during execution. Key moments include the necessity of express.json() middleware to parse JSON and handling invalid JSON gracefully. The quiz tests understanding of variable values at each step and how changes in input affect the flow.

Practice

(1/5)
1. What does the express.json() middleware do in an Express app?
easy
A. It sends JSON responses to the client.
B. It parses incoming JSON request bodies automatically.
C. It logs JSON data to the console.
D. It validates JSON schema in requests.

Solution

  1. Step 1: Understand middleware purpose

    The express.json() middleware is designed to parse JSON data sent in the request body.
  2. Step 2: Differentiate from response methods

    Sending JSON responses is done by res.json(), not express.json().
  3. Final Answer:

    It parses incoming JSON request bodies automatically. -> Option B
  4. Quick Check:

    express.json() parses JSON requests [OK]
Hint: express.json() parses JSON request bodies [OK]
Common Mistakes:
  • Confusing express.json() with res.json()
  • Thinking it sends JSON responses
  • Assuming it validates JSON schema
2. Which of the following is the correct way to send a JSON response with Express?
easy
A. res.sendJson({ message: 'Hello' })
B. res.send({ json: 'Hello' })
C. res.json({ message: 'Hello' })
D. res.jsonify({ message: 'Hello' })

Solution

  1. Step 1: Identify Express response methods

    Express provides res.json() to send JSON responses with proper headers.
  2. Step 2: Check method names

    Methods like sendJson or jsonify do not exist in Express.
  3. Final Answer:

    res.json({ message: 'Hello' }) -> Option C
  4. Quick Check:

    Use res.json() to send JSON responses [OK]
Hint: Use res.json() to send JSON responses [OK]
Common Mistakes:
  • Using non-existent methods like sendJson or jsonify
  • Using res.send() without JSON formatting
  • Confusing method names
3. Given this Express route, what will be the JSON response when a POST request with body { "name": "Alice" } is sent?
app.use(express.json());
app.post('/greet', (req, res) => {
  const user = req.body.name;
  res.json({ greeting: `Hello, ${user}!` });
});
medium
A. Empty response
B. { "greeting": "Hello, undefined!" }
C. SyntaxError
D. { "greeting": "Hello, Alice!" }

Solution

  1. Step 1: Parse JSON body with express.json()

    The middleware parses the JSON body, so req.body.name is 'Alice'.
  2. Step 2: Construct JSON response

    The response sends { greeting: `Hello, Alice!` } as JSON.
  3. Final Answer:

    { "greeting": "Hello, Alice!" } -> Option D
  4. Quick Check:

    Parsed JSON body used in res.json() response [OK]
Hint: express.json() parses body; res.json() sends response [OK]
Common Mistakes:
  • Forgetting to use express.json() middleware
  • Accessing req.body before parsing
  • Expecting undefined instead of 'Alice'
4. What is wrong with this Express code snippet for handling JSON requests?
app.post('/data', (req, res) => {
  const data = req.body;
  res.json({ received: data });
});
medium
A. Missing express.json() middleware to parse JSON body.
B. Using res.json() instead of res.send().
C. Incorrect route method; should be app.get.
D. No error; code works fine.

Solution

  1. Step 1: Check JSON parsing middleware

    The code accesses req.body but does not show express.json() middleware usage.
  2. Step 2: Understand middleware necessity

    Without express.json(), req.body will be undefined for JSON requests.
  3. Final Answer:

    Missing express.json() middleware to parse JSON body. -> Option A
  4. Quick Check:

    express.json() needed to parse JSON requests [OK]
Hint: Always add express.json() to parse JSON bodies [OK]
Common Mistakes:
  • Assuming req.body is parsed automatically
  • Confusing res.json() with res.send()
  • Using wrong HTTP method for JSON POST
5. You want to create an Express route that accepts a JSON array of numbers in the request body and responds with a JSON object containing the sum of those numbers. Which code snippet correctly implements this?
hard
A. app.post('/sum', express.json(), (req, res) => { const numbers = req.body; const sum = numbers.reduce((a, b) => a + b, 0); res.json({ sum }); });
B. app.post('/sum', (req, res) => { const numbers = JSON.parse(req.body); const sum = numbers.reduce((a, b) => a + b, 0); res.json({ sum }); });
C. app.post('/sum', express.urlencoded(), (req, res) => { const numbers = req.body; const sum = numbers.reduce((a, b) => a + b, 0); res.json({ sum }); });
D. app.post('/sum', (req, res) => { const numbers = req.body.numbers; const sum = numbers.reduce((a, b) => a + b, 0); res.send({ sum }); });

Solution

  1. 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 uses express.json() middleware inline to parse the JSON array in the request body.
  2. Step 2: Sum array and send JSON response

    It sums the numbers with reduce and sends the result with res.json(), which sets correct headers.
  3. 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 parse 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.
  4. 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 A
  5. Quick Check:

    express.json() + res.json() for JSON array sum [OK]
Hint: Use express.json() middleware and res.json() for JSON data [OK]
Common Mistakes:
  • 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