app.use(express.bodyParser());解析
发布于 3年前 作者 philsong 6529 次浏览

群里一位哥们问app.use(express.bodyParser());use是干嘛的,我跟踪了下源码,分析如下:

express.bodyParser()实际上是重用connect这个middleware中的bodyParser方法

 /** * Re-export connect auto-loaders. * * This prevents the need to require('connect') in order * to access core middleware, so for example express.logger() instead * of require('connect').logger(). */

    var exports = module.exports = connect.middleware;

bodyParser方法默认通过parser(req, options, next);支持json,, application/x-www-form-urlencoded, * and multipart/form-data 解析,否则传给解析链的下一个next()去解析。。 可以看出bodyParser是返回一个函数 return function bodyParser(req, res, next)

exports = module.exports = function bodyParser(options){ options = options || {}; return function bodyParser(req, res, next) { if (req.body) return next(); req.body = {};

if ('GET' == req.method || 'HEAD' == req.method) return next();
var parser = exports.parse[mime(req)];
if (parser) {
  parser(req, options, next);
} else {
  next();
}
} };

再看app.use,注意此处,express虽然继承了connect的use方法,但是又扩展导出了一个新方法,此方法的参数就是bodyParser()的返回值,从而实现了链式操作。

// expose objects to each other this.use(function(req, res, next){ req.query = req.query || {}; res.setHeader('X-Powered-By', 'Express'); req.app = res.app = self; req.res = res; res.req = req; req.next = next; // assign req.query if (req.url.indexOf('?') > 0) { var query = url.parse(req.url).query; req.query = qs.parse(query); } next(); });

至此,整个app.use的解析我们都清楚了:),不明白的再联系@我:)http://weibo.com/bocaicfa

回到顶部