Bird
0
0

Which code snippet correctly creates a Node.js HTTP server that responds with JSON {"message":"success"} and sets the appropriate headers?

hard📝 Application Q8 of 15
Node.js - HTTP Module
Which code snippet correctly creates a Node.js HTTP server that responds with JSON {"message":"success"} and sets the appropriate headers?
Aconst http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({message: 'success'})); }); server.listen(3000);
Bconst http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('{"message":"success"}'); }); server.listen(3000);
Cconst http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('<p>{"message":"success"}</p>'); }); server.listen(3000);
Dconst http = require('http'); const server = http.createServer((req, res) => { res.end(JSON.stringify({message: 'success'})); }); server.listen(3000);
Step-by-Step Solution
Solution:
  1. Step 1: Check Content-Type header

    For JSON responses, the header must be 'application/json'.
  2. Step 2: Check response body

    The body must be a stringified JSON object.
  3. Step 3: Verify code correctness

    const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, {'Content-Type': 'application/json'}); res.end(JSON.stringify({message: 'success'})); }); server.listen(3000); sets correct header and sends stringified JSON.
  4. Final Answer:

    Option A correctly sets header and sends JSON response. -> Option A
  5. Quick Check:

    Use 'application/json' and JSON.stringify() [OK]
Quick Trick: Set 'application/json' and stringify JSON [OK]
Common Mistakes:
  • Using 'text/plain' or 'text/html' for JSON
  • Sending raw JSON object without stringifying
  • Omitting Content-Type header

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes