http-json-response

send json responses easy

http-json-response

makes sending JSON over http a little more convenient

var send = require('http-json-response')
  , http = require('http')
 
http.createServer(function (reqres) {
  if (req.url === '/good') return send(res, {success: true})
  if (req.url === '/bad') return send(res, 500, {success: false})
  return send(res, 403, {success: 'kinda'})
}).listen(2100)

.. or if you're feeling particularly brazen

var http = require('http')
 
http.ServerResponse.prototype.send = require('http-json-response')
 
http.createServer(function (reqres) {
  if (req.url == '/good') return res.send({success: true})
  if (req.url == '/bad') return res.send(500, {success: false})
  return res.send(403, {success: 'kinda'})
}).listen(6666)

...at your own risk, of course.

  • adds in content-type: application/json header for you
  • send automatically calls res.end().
  • If the status code is not specified, it defaults to 200 (OK).

MIT