Bird
0
0

Given this Express.js route handler:

medium📝 Predict Output Q5 of 15
Rest API - HTTP Status Codes
Given this Express.js route handler:
app.get('/products/:id', (req, res) => {
  const products = { '100': 'Laptop', '200': 'Phone' };
  const product = products[req.params.id];
  if (!product) {
    res.status(404).send('Product not found');
  } else {
    res.send(product);
  }
});

What will be the HTTP status code if a client requests /products/300?
A200 OK
B500 Internal Server Error
C404 Not Found
D400 Bad Request
Step-by-Step Solution
Solution:
  1. Step 1: Check product existence

    Requesting /products/300 looks for key '300' in products object.
  2. Step 2: Product not found

    Since '300' is not a key, product is undefined, triggering the if condition.
  3. Step 3: Response status

    The handler sets status 404 and sends 'Product not found'.
  4. Final Answer:

    404 Not Found -> Option C
  5. Quick Check:

    Missing resource triggers 404 status. [OK]
Quick Trick: Missing resource returns 404, not 200 or 500 [OK]
Common Mistakes:
  • Assuming 200 OK even if resource is missing
  • Confusing 404 with server errors like 500
  • Not setting status before sending response

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes