form.js 1.2 KB

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