使用中间件与app.use
有什么区别:
function setLocale(req, res, next) { req.params.locale = req.params.locale || 'pt'; res.cookie('locale', req.params.locale); req.i18n.setLocale(req.params.locale); console.log(req.params.locale); next(); } app.get('/:locale?', setLocale, function(req, res) { res.render("index"); });
和这个:
app.use(setLocale); function setLocale(req, res, next) { req.params.locale = req.params.locale || 'pt'; res.cookie('locale', req.params.locale); req.i18n.setLocale(req.params.locale); console.log(req.params.locale); next(); } app.get('/:locale?', function(req, res) { res.render("index"); });
??
只有第一个工作,如果我尝试使用app.use,代码将打破原因req.params.locale将是未定义的。
问题是,当你使用app.use(setLocale);
你所调用的所有函数都会被传递。 即使你调用的URL /
该代码将运行,然后param将是未定义的。
你有() app.get('/:locale?', setLocale,
)你使用该函数只有当该url匹配,并有一个可以在该函数内使用的locale
。
app.use
会将中间件添加到堆栈中,并在每个请求处理之前使用它,而不pipe路由,方法等。
在第一个示例中,中间件仅作为callback函数添加到该路由中,因为app.get
接受多个callback,并且调用next
一个callback函数以执行下一个callback等
app.get('/', function(req, res, next) { next(); // move to next }, function(req, res, next) { // continues here when next() is called in previous callback etc. });
这意味着在第一个例子中,只有当path匹配/:locale?
时,才调用setLocale
函数/:locale?
而在第二个例子中,使用app.use
将始终在路由callback执行之前调用setLocale
函数。
不幸的是, req.params
在req.params
是不可用的,因为它依赖于路由器,并且稍后添加,所以您可能坚持将该函数作为callback函数包含在每条path中,您可以使用app.all('*')
function setLocale(req, res, next) { req.params.locale = req.params.locale || 'pt'; res.cookie('locale', req.params.locale); req.i18n.setLocale(req.params.locale); next(); } app.all('*', setLocale); app.get('/:locale?', function(req, res) { res.render("index"); });