4 * Copyright(c) 2010 Sencha Inc.
5 * Copyright(c) 2011 TJ Holowaychuk
10 * Module dependencies.
13 var qs = require('qs');
16 * Extract the mime type from the given request's
17 * _Content-Type_ header.
19 * @param {IncomingMessage} req
25 var str = req.headers['content-type'] || '';
26 return str.split(';')[0];
30 * Parse request bodies.
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.
39 * connect.createServer(
40 * connect.bodyParser()
41 * , function(req, res) {
42 * res.end('viewing user ' + req.body.user.name);
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".
50 * $ curl -d 'user[name]=tj' http://localhost/
51 * $ curl -d '{"user":{"name":"tj"}}' -H "Content-Type: application/json" http://localhost/
57 exports = module.exports = function bodyParser(){
58 return function bodyParser(req, res, next) {
59 var parser = exports.parse[mime(req)];
60 if (parser && !req.body) {
62 req.setEncoding('utf8');
63 req.on('data', function(chunk) { data += chunk; });
64 req.on('end', function(){
84 * - application/x-www-form-urlencoded
89 'application/x-www-form-urlencoded': qs.parse
90 , 'application/json': JSON.parse