Q11: What is the difference between `res.send()`, `res.json()`, and `res.end()`?

Difficulty:EasyTopic:Response Processing
  • res.send(): Generic response method. Accepts Buffer, String, Object, or Array. Automatically sets Content-Type header based on parameter type.
  • res.json(): Explicitly formats input parameter using JSON.stringify() and explicitly sets Content-Type: application/json header. Converts null and undefined to valid JSON.
  • res.end(): Node native method used to end response cycle quickly without sending data or auto-setting headers. Useful for 204 No Content responses.
Key Takeaways
  • Use res.json() when building RESTful APIs to guarantee proper JSON response headers.

  • res.send() invokes res.json() internally when passed an Object or Array.