Bird
0
0

You have this Express.js route handler:

medium📝 Debug Q14 of 15
Rest API - HTTP Status Codes
You have this Express.js route handler:
app.get('/users/:id', (req, res) => {
  const users = {1: 'Alice', 2: 'Bob'};
  const user = users[req.params.id];
  if (!user) {
    res.status(404);
  }
  res.send(user);
});

What is the problem with this code when a user is not found?
AIt correctly sends a 404 status with no body.
BIt sends a 404 status but still sends undefined as response body.
CIt throws a syntax error due to missing semicolon.
DIt sends a 500 Internal Server Error automatically.
Step-by-Step Solution
Solution:
  1. Step 1: Analyze response when user not found

    res.status(404) sets status but does not end response or send body.
  2. Step 2: Check what res.send(user) does

    res.status(404) sets the status, but execution continues to res.send(undefined), which sends the string 'undefined' as body with 404 status.
  3. Final Answer:

    It sends a 404 status but still sends undefined as response body. -> Option B
  4. Quick Check:

    Missing res.send after status causes wrong response [OK]
Quick Trick: Always send response body or end response after setting status [OK]
Common Mistakes:
  • Setting status without sending response body
  • Assuming status alone ends response
  • Not checking for undefined response body

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes