Tizen 2.0 Release
[platform/framework/web/web-ui-fw.git] / libs / js / jquery-mobile-1.2.0 / node_modules / grunt / node_modules / connect / lib / middleware / urlencoded.js
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
13 var utils = require('../utils')
14   , _limit = require('./limit')
15   , qs = require('qs');
16
17 /**
18  * noop middleware.
19  */
20
21 function 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
40 exports = 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     // check Content-Type
52     if ('application/x-www-form-urlencoded' != utils.mime(req)) return next();
53
54     // flag as parsed
55     req._body = true;
56
57     // parse
58     limit(req, res, function(err){
59       if (err) return next(err);
60       var buf = '';
61       req.setEncoding('utf8');
62       req.on('data', function(chunk){ buf += chunk });
63       req.on('end', function(){
64         try {
65           req.body = buf.length
66             ? qs.parse(buf, options)
67             : {};
68           next();
69         } catch (err){
70           err.body = buf;
71           next(err);
72         }
73       });
74     });
75   }
76 };