app.use(express.bodyParser());解析
发布于 10 年前 作者 philsong 33646 次浏览 最后一次编辑是 5 年前

群里一位哥们问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

5 回复

现在关于这个app.use(express.bodyParser()) 是不是不能直接使用了? 得要使用下面的module? var bodyParser = require(‘body-parser’) app.use(bodyParser.urlencoded({extended: true}))

@kylezhang 是的,最新本里已经移除了。

谁知道extend:true有什么用吗

@githubmann 官方文档的解释,挺清楚的: The extended option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). The “extended” syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded. For more information, please see the qs library.

回到顶部