Bird
0
0

Examine this Node.js server code snippet for manual routing:

medium📝 Debug Q6 of 15
Node.js - HTTP Module
Examine this Node.js server code snippet for manual routing:
const http = require('http');
const server = http.createServer((req, res) => {
  if (req.url == '/home') {
    res.write('Welcome Home');
    res.end();
  }
});
server.listen(3000);

What is the main issue with this code?
AUsing '==' instead of '===' for URL comparison
BMissing res.writeHead() to set status and headers
CNot calling res.end() after writing response
DServer is not listening on the specified port
Step-by-Step Solution
Solution:
  1. Step 1: Check URL comparison

    The code uses '==' which works but '===' is preferred for strict equality.
  2. Step 2: Check response headers

    res.writeHead() is missing, so status code and content-type headers are not set, which can cause issues.
  3. Step 3: Check response ending

    res.end() is correctly called, so response ends properly.
  4. Final Answer:

    Missing res.writeHead() to set status and headers -> Option B
  5. Quick Check:

    Headers must be set before writing body [OK]
Quick Trick: Always set headers with res.writeHead() before res.write() [OK]
Common Mistakes:
  • Using '==' instead of '===' causes bugs
  • Forgetting to call res.end()
  • Not setting response headers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes