Bird
0
0

What is wrong with this Node.js code snippet that tries to read JSON data from the request body?

medium📝 Debug Q14 of 15
Node.js - HTTP Module
What is wrong with this Node.js code snippet that tries to read JSON data from the request body?
const http = require('http');
const server = http.createServer((req, res) => {
  const data = req.body;
  res.end(data);
});
server.listen(3000);
Ares.end cannot send data
Breq.body is undefined without parsing the data
Creq.body is a function, not a property
DMissing require for http module
Step-by-Step Solution
Solution:
  1. Step 1: Understand how request body works in Node.js

    In Node.js core, req.body is not automatically populated. You must collect data chunks and parse them manually or use middleware.
  2. Step 2: Identify the error in the code

    The code tries to access req.body directly, which will be undefined, causing the response to send undefined.
  3. Final Answer:

    req.body is undefined without parsing the data -> Option B
  4. Quick Check:

    req.body needs manual parsing [OK]
Quick Trick: req.body is empty unless parsed manually or with middleware [OK]
Common Mistakes:
  • Assuming req.body is auto-filled in Node.js core
  • Trying to send undefined data without error
  • Confusing res.end usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes