Permalink
Browse files

misc

  • Loading branch information...
1 parent 11851b0 commit 32f4fc17669a02b0ca3e8caa3116f02e7eb9b293 @tj tj committed Nov 17, 2011
Showing with 38 additions and 20 deletions.
  1. +38 −20 lib/middleware/bodyParser.js
@@ -62,33 +62,51 @@ exports = module.exports = function bodyParser(){
if ('GET' == req.method || 'HEAD' == req.method) return next();
var parser = exports.parse[mime(req)];
if (parser) {
- var data = '';
- req.setEncoding('utf8');
- req.on('data', function(chunk) { data += chunk; });
- req.on('end', function(){
- try {
- req.body = data
- ? parser(data)
- : {};
- } catch (err) {
- return next(err);
- }
- next();
- });
+ parser(req, next);
} else {
next();
}
}
};
/**
- * Supported decoders.
- *
- * - application/x-www-form-urlencoded
- * - application/json
+ * Parsers.
+ */
+
+exports.parse = {};
+
+/**
+ * Parse x-www-form-urlencoded.
+ */
+
+exports.parse['application/x-www-form-urlencoded'] = function(req, fn){
+ var buf = '';
+ req.setEncoding('utf8');
+ req.on('data', function(chunk){ buf += chunk });
+ req.on('end', function(){
+ try {
+ req.body = qs.parse(buf);
+ fn();
+ } catch (err){
+ fn(err);
+ }
+ });
+};
+
+/**
+ * Parse application/json.
*/
-exports.parse = {
- 'application/x-www-form-urlencoded': qs.parse
- , 'application/json': JSON.parse
+exports.parse['application/json'] = function(req, fn){
+ var buf = '';
+ req.setEncoding('utf8');
+ req.on('data', function(chunk){ buf += chunk });
+ req.on('end', function(){
+ try {
+ req.body = JSON.parse(buf);
+ fn();
+ } catch (err){
+ fn(err);
+ }
+ });
};

0 comments on commit 32f4fc1

Please sign in to comment.