Bird
0
0

You have this Express.js code snippet:

medium📝 Debug Q6 of 15
Rest API - HTTP Status Codes
You have this Express.js code snippet:
app.post('/users', (req, res) => {
  if (!req.body.email) {
    res.status(422).send({ error: 'Email is required' });
  } else {
    res.status(201).send({ message: 'User created' });
  }
});

What is the problem if the client sends an empty JSON body?
AThe server correctly returns 422 because email is missing
BThe server returns 201 even if email is missing
CThe server crashes due to missing email
DThe server returns 400 Bad Request instead of 422
Step-by-Step Solution
Solution:
  1. Step 1: Check the condition for missing email

    The code checks if req.body.email is missing and returns 422 with an error message.
  2. Step 2: Analyze behavior with empty JSON

    Empty JSON means no email field, so the condition triggers and 422 is returned correctly.
  3. Final Answer:

    The server correctly returns 422 because email is missing -> Option A
  4. Quick Check:

    Missing required field triggers 422 response [OK]
Quick Trick: Check required fields and return 422 if missing [OK]
Common Mistakes:
  • Assuming server crashes on missing fields
  • Expecting 201 success despite missing data
  • Confusing 422 with 400 Bad Request

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Rest API Quizzes