form.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. /**
  2. * Module dependencies.
  3. */
  4. var raw = require('raw-body');
  5. var inflate = require('inflation');
  6. var qs = require('qs');
  7. /**
  8. * Return a Promise which parses x-www-form-urlencoded requests.
  9. *
  10. * Pass a node request or an object with `.req`,
  11. * such as a koa Context.
  12. *
  13. * @param {Request} req
  14. * @param {Options} [opts]
  15. * @return {Function}
  16. * @api public
  17. */
  18. module.exports = function(req, opts){
  19. req = req.req || req;
  20. opts = opts || {};
  21. // defaults
  22. var len = req.headers['content-length'];
  23. var encoding = req.headers['content-encoding'] || 'identity';
  24. if (len && encoding === 'identity') opts.length = ~~len;
  25. opts.encoding = opts.encoding || 'utf8';
  26. opts.limit = opts.limit || '56kb';
  27. opts.qs = opts.qs || qs;
  28. // raw-body returns a Promise when no callback is specified
  29. return raw(inflate(req), opts)
  30. .then(function(str){
  31. try {
  32. return opts.qs.parse(str, opts.queryString);
  33. } catch (err) {
  34. err.status = 400;
  35. err.body = str;
  36. throw err;
  37. }
  38. });
  39. };