186
Ft
fractal-tree / files
fractal-tree / node_modules / connect / lib / middleware / bodyParser.js
2.1 KB
1 2/*! 3 * Connect - bodyParser 4 * Copyright(c) 2010 Sencha Inc. 5 * Copyright(c) 2011 TJ Holowaychuk 6 * MIT Licensed 7 */ 8 9/** 10 * Module dependencies. 11 */ 12 13var qs = require('qs'); 14 15/** 16 * Extract the mime type from the given request's 17 * _Content-Type_ header. 18 * 19 * @param {IncomingMessage} req 20 * @return {String} 21 * @api private 22 */ 23 24function mime(req) { 25 var str = req.headers['content-type'] || ''; 26 return str.split(';')[0]; 27} 28 29/** 30 * Parse request bodies. 31 * 32 * By default _application/json_ and _application/x-www-form-urlencoded_ 33 * are supported, however you may map `connect.bodyParser.parse[contentType]` 34 * to a function of your choice to replace existing parsers, or implement 35 * one for other content-types. 36 * 37 * Examples: 38 * 39 * connect.createServer( 40 * connect.bodyParser() 41 * , function(req, res) { 42 * res.end('viewing user ' + req.body.user.name); 43 * } 44 * ); 45 * 46 * Since both _json_ and _x-www-form-urlencoded_ are supported by 47 * default, either of the following requests would result in the response 48 * of "viewing user tj". 49 * 50 * $ curl -d 'user[name]=tj' http://localhost/ 51 * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://localhost/ 52 * 53 * @return {Function} 54 * @api public 55 */ 56 57exports = module.exports = function bodyParser(){ 58 return function bodyParser(req, res, next) { 59 if ('GET' == req.method || 'HEAD' == req.method) return next(); 60 var parser = exports.parse[mime(req)]; 61 if (parser && !req.body) { 62 var data = ''; 63 req.setEncoding('utf8'); 64 req.on('data', function(chunk) { data += chunk; }); 65 req.on('end', function(){ 66 req.rawBody = data; 67 try { 68 req.body = data 69 ? parser(data) 70 : {}; 71 } catch (err) { 72 return next(err); 73 } 74 next(); 75 }); 76 } else { 77 next(); 78 } 79 } 80}; 81 82/** 83 * Supported decoders. 84 * 85 * - application/x-www-form-urlencoded 86 * - application/json 87 */ 88 89exports.parse = { 90 'application/x-www-form-urlencoded': qs.parse 91 , 'application/json': JSON.parse 92};