Nodejs Express隐式中间件适用于所有路由吗? [英] Nodejs Express implicit middleware applied to all routes?
本文介绍了Nodejs Express隐式中间件适用于所有路由吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道Express是否可以让我创建一个路由中间件,而无需我将其显式地放置在app.get()arg列表中吗?
I wanted to know if Express would let me create a route middleware that would be called by default without me explicitly placing it on the app.get() arg list?
//NodeJS newb
// NodeJS newb
var data = { title: 'blah' };
// So I want to include this in every route
function a(){
return function(req, res){
req.data = data;
};
};
app.get('/', function(req, res) {
res.render('index', { title: req.data.title });
};
我知道我可以执行app.set('data', data)
并通过路由中的req.app.settings.data
访问它.这可能会满足我上面的简单示例.
I understand I can do app.set('data', data)
and access it via req.app.settings.data
in the route. Which would probably satisfy my simple example above.
推荐答案
function a(req, res, next){
req.data = data;
// Update: based on latest version of express, better use this
res.locals.data = data;
next();
};
app.get('/*', a);
请参见快速文档,中间件"部分中的示例.
这篇关于Nodejs Express隐式中间件适用于所有路由吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文