Nodejs Express隐式中间件应用于所有路由?

Mat*_*agg 2 node.js express

我想知道Express是否会让我创建一个默认调用的路由中间件,而不是我明确地将它放在app.get()arg列表中?

// 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 });
};
Run Code Online (Sandbox Code Playgroud)

我知道我可以做app.set('data', data),并通过req.app.settings.data路线访问它.哪个可能满足我上面的简单例子.

Mat*_*all 9

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);
Run Code Online (Sandbox Code Playgroud)

请参阅Express docs,Middleware部分中的示例.

  • 你可能想要将它映射到app.all,以确保它也为post请求执行. (8认同)