Nodejs Express implicit middleware applied to all routes?

强颜欢笑 提交于 2020-04-13 07:58:32

问题


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

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 });
};

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.


回答1:


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);

See the examples on the Express docs, Middleware section.




回答2:


You can create a default way to call every view you have made without have to explicit create a new route for every new entry. Check out this following example:

app.get('/:viewname', function(req, res) {
    res.render(req.params.viewname, { viewname : req.params.viewname});
});

I hope it's you're looking forward.




回答3:


You can also do it this way:

function my_middleware(req, res, next){
   req.data = data;

   if (something(res)) redirect('http://google.com'); // no access to your site
   next(); // go to routes

};

app.configure(function() {
   ...
   app.use(express.cookieParser('secret'));
   app.use(express.session());
   app.use(my_middleware);
   app.use(app.router);
   ...
}

In this case my_middleware is called when cookies and sessions are already available, but no routes are processed yet. Or you can even do it before session if you need it for some reason.



来源:https://stackoverflow.com/questions/10356311/nodejs-express-implicit-middleware-applied-to-all-routes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!