Bird
0
0

Given this code snippet, what will be the response if the client requests '/api/data'?

medium📝 component behavior Q5 of 15
Node.js - HTTP Module
Given this code snippet, what will be the response if the client requests '/api/data'?
const http = require('http');
const server = http.createServer((req, res) => {
  switch(req.url) {
    case '/api/data':
      res.writeHead(200, {'Content-Type': 'application/json'});
      res.end(JSON.stringify({data: 'info'}));
      break;
    default:
      res.writeHead(404);
      res.end('Not Found');
  }
});
server.listen(3000);
Aundefined
BNot Found
CError: Unexpected token
D{"data":"info"}
Step-by-Step Solution
Solution:
  1. Step 1: Match the URL '/api/data'

    The switch case matches '/api/data' and sets status 200 with JSON content type.
  2. Step 2: Send JSON stringified data

    The response sends a JSON string: '{"data":"info"}'.
  3. Final Answer:

    {"data":"info"} -> Option D
  4. Quick Check:

    JSON response for '/api/data' = JSON string [OK]
Quick Trick: Use JSON.stringify to send JSON responses [OK]
Common Mistakes:
  • Sending object directly without stringify
  • Missing res.end() causes no response
  • Wrong content-type header

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes