xonecas.io
142
St

startsInvasion / files

startsInvasion / libs / node_modules / reqwest / build / connect / lib / middleware / bodyParser.js

2.0 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    var parser = exports.parse[mime(req)];
60    if (parser && !req.body) {
61      var data = '';
62      req.setEncoding('utf8');
63      req.on('data', function(chunk) { data += chunk; });
64      req.on('end', function(){
65        req.rawBody = data;
66        try {
67          req.body = data
68            ? parser(data)
69            : {};
70        } catch (err) {
71          return next(err);
72        }
73        next();
74      });
75    } else {
76      next();
77    }
78  }
79};
80
81/**
82 * Supported decoders.
83 *
84 *  - application/x-www-form-urlencoded
85 *  - application/json
86 */
87
88exports.parse = {
89    'application/x-www-form-urlencoded': qs.parse
90  , 'application/json': JSON.parse
91};