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.

78 lines
1.4 KiB

  1. /*!
  2. * Connect - urlencoded
  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. , qs = require('qs');
  13. /**
  14. * noop middleware.
  15. */
  16. function noop(req, res, next) {
  17. next();
  18. }
  19. /**
  20. * Urlencoded:
  21. *
  22. * Parse x-ww-form-urlencoded request bodies,
  23. * providing the parsed object as `req.body`.
  24. *
  25. * Options:
  26. *
  27. * - `limit` byte limit disabled by default
  28. *
  29. * @param {Object} options
  30. * @return {Function}
  31. * @api public
  32. */
  33. exports = module.exports = function(options){
  34. options = options || {};
  35. var limit = options.limit
  36. ? _limit(options.limit)
  37. : noop;
  38. return function urlencoded(req, res, next) {
  39. if (req._body) return next();
  40. req.body = req.body || {};
  41. if (!utils.hasBody(req)) return next();
  42. // check Content-Type
  43. if ('application/x-www-form-urlencoded' != utils.mime(req)) return next();
  44. // flag as parsed
  45. req._body = true;
  46. // parse
  47. limit(req, res, function(err){
  48. if (err) return next(err);
  49. var buf = '';
  50. req.setEncoding('utf8');
  51. req.on('data', function(chunk){ buf += chunk });
  52. req.on('end', function(){
  53. try {
  54. req.body = buf.length
  55. ? qs.parse(buf, options)
  56. : {};
  57. next();
  58. } catch (err){
  59. err.body = buf;
  60. next(err);
  61. }
  62. });
  63. });
  64. }
  65. };