Bird
0
0

Identify the error in this Node.js code that tries to set a response header:

medium📝 Debug Q14 of 15
Node.js - HTTP Module
Identify the error in this Node.js code that tries to set a response header:
const http = require('http');
const server = http.createServer((req, res) => {
  res.write('Hello');
  res.setHeader('Content-Type', 'text/plain');
  res.end();
});
server.listen(3000);
Ares.end() is missing a parameter
BThe method setHeader does not exist on res
CHeaders must be set before writing the response body
DThe server.listen port number is invalid
Step-by-Step Solution
Solution:
  1. Step 1: Check order of header setting and response writing

    Headers must be set before sending any part of the response body.
  2. Step 2: Identify the error in code order

    res.write('Hello') sends body first, so setHeader after it causes error.
  3. Final Answer:

    Headers must be set before writing the response body -> Option C
  4. Quick Check:

    Set headers before body [OK]
Quick Trick: Set headers before any res.write or res.end [OK]
Common Mistakes:
  • Setting headers after writing body
  • Thinking setHeader is invalid method
  • Assuming res.end needs data always

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes