comunicationLeap/node_modules/connect/lib/middleware/urlencoded.js
node_modules/connect/lib/middleware/urlencoded.jsRaw
1
2/*!
3 * Connect - urlencoded
4 * Copyright(c) 2010 Sencha Inc.
5 * Copyright(c) 2011 TJ Holowaychuk
6 * MIT Licensed
7 */
8
9/**
10 * Module dependencies.
11 */
12
13var utils = require('../utils')
14 , _limit = require('./limit')
15 , qs = require('qs');
16
17/**
18 * noop middleware.
19 */
20
21function noop(req, res, next) {
22 next();
23}
24
25/**
26 * Urlencoded:
27 *
28 * Parse x-ww-form-urlencoded request bodies,
29 * providing the parsed object as `req.body`.
30 *
31 * Options:
32 *
33 * - `limit` byte limit disabled by default
34 *
35 * @param {Object} options
36 * @return {Function}
37 * @api public
38 */
39
40exports = module.exports = function(options){
41 options = options || {};
42
43 var limit = options.limit
44 ? _limit(options.limit)
45 : noop;
46
47 return function urlencoded(req, res, next) {
48 if (req._body) return next();
49 req.body = req.body || {};
50
51 if (!utils.hasBody(req)) return next();
52
53 // check Content-Type
54 if ('application/x-www-form-urlencoded' != utils.mime(req)) return next();
55
56 // flag as parsed
57 req._body = true;
58
59 // parse
60 limit(req, res, function(err){
61 if (err) return next(err);
62 var buf = '';
63 req.setEncoding('utf8');
64 req.on('data', function(chunk){ buf += chunk });
65 req.on('end', function(){
66 try {
67 req.body = buf.length
68 ? qs.parse(buf, options)
69 : {};
70 next();
71 } catch (err){
72 err.body = buf;
73 next(err);
74 }
75 });
76 });
77 }
78};