Bird
Raised Fist0
Node.jsframework~10 mins

Status code usage patterns in Node.js - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Status code usage patterns
Receive HTTP Request
↓
Process Request Logic
↓
Determine Status Code
↓
Set Response Status Code
↓
Send Response with Status Code
↓
Client Receives Response
↓
Client Handles Based on Status Code
This flow shows how a Node.js server receives a request, decides the right status code, sends it back, and how the client uses it.
Execution Sample
Node.js
import http from 'http';

const server = http.createServer((req, res) => {
  if (req.url === '/success') {
    res.statusCode = 200;
    res.end('OK');
  } else {
    res.statusCode = 404;
    res.end('Not Found');
  }
});

server.listen(3000);
A simple Node.js server that sends 200 for '/success' and 404 for other URLs.
Execution Table
StepRequest URLConditionStatus Code SetResponse Sent
1/successreq.url === '/success' is true200'OK'
2/unknownreq.url === '/success' is false404'Not Found'
3-No more requests--
💡 No more requests to process, server keeps running.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
req.urlundefined/success/unknownvaries per request
res.statusCode200 (default)200404varies per request
res.end()not calledcalled with 'OK'called with 'Not Found'called per request
Key Moments - 3 Insights
Why do we set res.statusCode before calling res.end()?
Because the status code must be set before sending the response body; see execution_table rows 1 and 2 where statusCode is set before res.end() is called.
What happens if we don't set a status code explicitly?
Node.js defaults to 200 OK if no status code is set; this is why res.statusCode starts at 200 in variable_tracker.
Why does the server send 404 for unknown URLs?
Because the condition req.url === '/success' is false, so the else branch sets statusCode to 404 and sends 'Not Found' as shown in execution_table row 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what status code is sent when the request URL is '/success'?
A404
B500
C200
D301
💡 Hint
Check execution_table row 1 under 'Status Code Set'
At which step does the server send a 'Not Found' response?
AStep 1
BStep 2
CStep 3
DNo step sends 'Not Found'
💡 Hint
Look at execution_table row 2 under 'Response Sent'
If we add a new URL '/error' that sets statusCode to 500, how would the execution_table change?
AAdd a new row with statusCode 500 and appropriate response
BChange step 1 statusCode to 500
CRemove step 2
DNo change needed
💡 Hint
New request URLs add new rows as seen in execution_table rows 1 and 2
Concept Snapshot
Status code usage in Node.js:
- Set res.statusCode before res.end()
- 200 means success
- 404 means resource not found
- Use status codes to tell client what happened
- Always send a response to end request
- Status codes guide client behavior
Full Transcript
This visual execution shows how a Node.js server handles HTTP requests by checking the URL, setting the right status code, and sending a response. When the URL is '/success', the server sets status code 200 and sends 'OK'. For other URLs, it sets 404 and sends 'Not Found'. The status code must be set before sending the response body. If no status code is set, Node.js defaults to 200. This pattern helps clients understand if their request succeeded or failed. The execution table tracks each step, showing the request URL, condition checked, status code set, and response sent. Variable tracker shows how request URL and response status code change per request. Key moments clarify why order matters and why 404 is sent for unknown URLs. The quiz tests understanding of status codes sent at each step and how adding new URLs affects the flow.

Practice

(1/5)
1. What does the HTTP status code 200 generally indicate in a Node.js response?
easy
A. The client made a bad request with invalid syntax.
B. The request was successful and the server returned the requested data.
C. The requested resource was not found on the server.
D. The server encountered an internal error.

Solution

  1. Step 1: Understand HTTP status codes

    HTTP status codes communicate the result of a client's request to the server.
  2. Step 2: Identify the meaning of 200

    Status code 200 means the request succeeded and the server sent back the expected data.
  3. Final Answer:

    The request was successful and the server returned the requested data. -> Option B
  4. Quick Check:

    200 = Success [OK]
Hint: 200 means success, data sent back properly [OK]
Common Mistakes:
  • Confusing 200 with error codes like 400 or 500
  • Thinking 200 means resource not found
  • Mixing up client and server error codes
2. Which of the following is the correct way to set a 404 status code in a Node.js Express response?
easy
A. res.status(404).send('Not Found');
B. res.sendStatus(404, 'Not Found');
C. res.code(404).send('Not Found');
D. res.setStatus(404).send('Not Found');

Solution

  1. Step 1: Recall Express response methods

    Express uses res.status(code) to set status codes before sending a response.
  2. Step 2: Check method correctness

    res.status(404).send('Not Found'); correctly sets status 404 and sends the message.
  3. Final Answer:

    res.status(404).send('Not Found'); -> Option A
  4. Quick Check:

    Use res.status(code) to set status [OK]
Hint: Use res.status(code) before sending response [OK]
Common Mistakes:
  • Using non-existent methods like res.code or res.setStatus
  • Passing status code as second argument to send
  • Confusing sendStatus with status
3. Consider this Express code snippet:
app.get('/data', (req, res) => {
  if (!req.query.id) {
    return res.status(400).send('Missing id');
  }
  res.status(200).send('Data for ' + req.query.id);
});

What status code will the server respond with if the client calls /data without an id query parameter?
medium
A. 400
B. 404
C. 200
D. 500

Solution

  1. Step 1: Analyze the condition for missing id

    The code checks if req.query.id is missing and returns status 400 with message 'Missing id'.
  2. Step 2: Determine response when id is missing

    If id is absent, the server responds immediately with status 400 (bad request).
  3. Final Answer:

    400 -> Option A
  4. Quick Check:

    Missing required data = 400 [OK]
Hint: Missing required input usually means 400 Bad Request [OK]
Common Mistakes:
  • Assuming 404 means missing query parameter
  • Thinking 200 is always returned
  • Confusing 500 server error with client error
4. You have this Express route:
app.post('/submit', (req, res) => {
  if (!req.body.name) {
    res.sendStatus(422);
  }
  res.status(201).send('Created');
});

What is the problem with this code?
medium
A. It should use res.status(400) instead of 422.
B. The status code 422 is not valid in HTTP.
C. The res.status(201) should come before the if block.
D. It sends two responses if name is missing, causing an error.

Solution

  1. Step 1: Check response flow when name is missing

    If !req.body.name is true, res.sendStatus(422) sends a response but code continues.
  2. Step 2: Identify double response issue

    After sending 422, the code still calls res.status(201).send('Created'), causing an error because response was already sent.
  3. Final Answer:

    It sends two responses if name is missing, causing an error. -> Option D
  4. Quick Check:

    Send response once per request [OK]
Hint: Return after sending response to avoid double sends [OK]
Common Mistakes:
  • Not returning after sending a response
  • Confusing 422 with invalid status code
  • Thinking order of status calls matters without return
5. You want to create an Express route that returns a JSON error with status 403 if the user is not authorized, and status 200 with data if authorized. Which code snippet correctly implements this pattern?
hard
A. app.get('/secret', (req, res) => { if (!req.user) { res.status(403).json({ error: 'Forbidden' }); } res.status(200).json({ data: 'Secret info' }); });
B. app.get('/secret', (req, res) => { if (!req.user) { res.sendStatus(403); } else { res.sendStatus(200).json({ data: 'Secret info' }); } });
C. app.get('/secret', (req, res) => { if (!req.user) { return res.status(403).json({ error: 'Forbidden' }); } res.status(200).json({ data: 'Secret info' }); });
D. app.get('/secret', (req, res) => { if (!req.user) { res.status(403).send('Forbidden'); } res.status(200).send('Secret info'); });

Solution

  1. Step 1: Check response flow for unauthorized user

    app.get('/secret', (req, res) => { if (!req.user) { return res.status(403).json({ error: 'Forbidden' }); } res.status(200).json({ data: 'Secret info' }); }); uses return after sending 403 JSON error, preventing further code execution.
  2. Step 2: Confirm authorized user response

    It sends status 200 with JSON data correctly if user exists.
  3. Final Answer:

    app.get('/secret', (req, res) => { if (!req.user) { return res.status(403).json({ error: 'Forbidden' }); } res.status(200).json({ data: 'Secret info' }); }); -> Option C
  4. Quick Check:

    Return after error response to avoid double sends [OK]
Hint: Use return after error response to stop execution [OK]
Common Mistakes:
  • Not returning after sending error response
  • Using sendStatus with json chaining incorrectly
  • Sending plain text instead of JSON for API
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard