You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

86 lines
1.8 KiB

  1. /*!
  2. * Connect - json
  3. * Copyright(c) 2010 Sencha Inc.
  4. * Copyright(c) 2011 TJ Holowaychuk
  5. * MIT Licensed
  6. */
  7. /**
  8. * Module dependencies.
  9. */
  10. var utils = require('../utils')
  11. , _limit = require('./limit');
  12. /**
  13. * noop middleware.
  14. */
  15. function noop(req, res, next) {
  16. next();
  17. }
  18. /**
  19. * JSON:
  20. *
  21. * Parse JSON request bodies, providing the
  22. * parsed object as `req.body`.
  23. *
  24. * Options:
  25. *
  26. * - `strict` when `false` anything `JSON.parse()` accepts will be parsed
  27. * - `reviver` used as the second "reviver" argument for JSON.parse
  28. * - `limit` byte limit disabled by default
  29. *
  30. * @param {Object} options
  31. * @return {Function}
  32. * @api public
  33. */
  34. exports = module.exports = function(options){
  35. var options = options || {}
  36. , strict = options.strict !== false;
  37. var limit = options.limit
  38. ? _limit(options.limit)
  39. : noop;
  40. return function json(req, res, next) {
  41. if (req._body) return next();
  42. req.body = req.body || {};
  43. if (!utils.hasBody(req)) return next();
  44. // check Content-Type
  45. if ('application/json' != utils.mime(req)) return next();
  46. // flag as parsed
  47. req._body = true;
  48. // parse
  49. limit(req, res, function(err){
  50. if (err) return next(err);
  51. var buf = '';
  52. req.setEncoding('utf8');
  53. req.on('data', function(chunk){ buf += chunk });
  54. req.on('end', function(){
  55. var first = buf.trim()[0];
  56. if (0 == buf.length) {
  57. return next(utils.error(400, 'invalid json, empty body'));
  58. }
  59. if (strict && '{' != first && '[' != first) return next(utils.error(400, 'invalid json'));
  60. try {
  61. req.body = JSON.parse(buf, options.reviver);
  62. } catch (err){
  63. err.body = buf;
  64. err.status = 400;
  65. return next(err);
  66. }
  67. next();
  68. });
  69. });
  70. };
  71. };