简体   繁体   English

如果通过了Express / Node JS认证,则将用户数据放入所有路由

[英]putting User data in all routes if authenticated Express/Node JS

I'm wondering if there is a way to put user data available in session, in response of routes by default. 我想知道是否有一种方法可以将用户数据置于会话中,以默认情况下响应路由。 For example writing something like this: 例如,编写如下内容:

app.get("/someRandomPath",PutUserData,function(req,res,next)
{
  res.render("myView",{title:"my page title"})
}

function PutUserData(req,res,next)
{
  if(auth)
  {
   res.send({user:session.user}
   next()
  }
  else next()
}

or even better do something in application level such as app.use(...) ? 甚至更好地在应用程序级别执行诸如app.use(...) The reason I want to do this is I want to avoid checking if user is Authed or not in every single route and render views with different data. 我要这样做的原因是,我想避免在每个路由中都检查用户是否经过身份验证,并使用不同的数据呈现视图。 I'd appreciate your help. 多谢您的协助。

Check out res.locals from the Express documentation. 从Express文档中查看res.locals That could work for you. 那可以为您工作。

http://expressjs.com/en/api.html#res.locals http://expressjs.com/en/api.html#res.locals

Also, see this answer for help understanding how res.locals works. 另外,请参阅此答案以帮助了解res.locals的工作原理。

 app.use(function(req, res, next){
   res.locals.user = session.user;
   next();
 });

front-end (jade template but you can use whatever templating engine you want) 前端(玉器模板,但您可以使用所需的任何模板引擎)

extends layout

block content   
  p user was set to #{user}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM