Bird
0
0

You want to build a Node.js HTTP server that responds with JSON data and handles errors gracefully. Which approach is best?

hard📝 state output Q15 of 15
Node.js - HTTP Module
You want to build a Node.js HTTP server that responds with JSON data and handles errors gracefully. Which approach is best?
AUse http.createServer, set Content-Type to application/json, but do not handle errors.
BUse http.createServer, send JSON as plain text, ignore errors to keep server fast.
CUse http.createServer, set Content-Type to text/html, and send JSON string directly.
DUse http.createServer, set Content-Type to application/json, and wrap response code in try-catch.
Step-by-Step Solution
Solution:
  1. Step 1: Set correct Content-Type for JSON

    To send JSON, Content-Type must be 'application/json' so clients parse it properly.
  2. Step 2: Handle errors gracefully

    Wrapping response code in try-catch prevents server crashes and sends error info.
  3. Final Answer:

    Use http.createServer, set Content-Type to application/json, and wrap response code in try-catch. -> Option D
  4. Quick Check:

    JSON needs correct header + error handling [OK]
Quick Trick: Always set JSON header and catch errors in server code [OK]
Common Mistakes:
  • Sending JSON with wrong Content-Type
  • Ignoring errors causing server crashes
  • Using text/html header for JSON data

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes