Node.js检测用户访问的每个页面的req中是否存在变量

Node.js detect if a variable exists in req for every page a user goes to

本文关键字:req 是否 变量 存在 检测 js 用户 访问 Node      更新时间:2023-09-26

更具体地说,我有一个使用passportjs的认证系统,如果用户经过身份验证,则定义req.user

现在我的网站只有大约5个页面,但它正在增长,在每条路线的顶部,我检查req.user是否存在,我传递一个true或false变量到渲染模板,模板相应地渲染。

我搞砸了东西,如app.get("*"),但我没有找到任何好。

我怎么能检查如果req.user(或任何其他可能存在于req…)存在-当用户去我的网站的任何页面,没有重复的代码?

进步:

app.js中使用此代码:

app.use(function (req, res, next) {
  // Using req.locals.isAuthenticated would be better, as it's automatically passed to every rendered templates.
  req.context = {};
  req.context.isLoggedIn = req.isAuthenticated();
  // req.locals.isAuthenticated = req.isAuthenticated();
  next();
});
app.use('/dashboard', dashboard);

routes/dashboard路由:

router.get('/', function (req, res) {
  res.render('dashboard', { isLoggedIn: req.context.isLoggedIn });
});

Works -然后我可以通过执行例如{{ isLoggedIn }}来查看用户是否登录。

但是,当我取消注释请求时。在第一个代码片段的locals行中,我得到一个500的错误。

有两点需要注意:

  • 通常当你的应用程序需要为一堆不同的页面做一些事情时,你想通过app.use

  • 设置一个中间件功能
  • Express有一个res.locals变量,它的属性将被包含在任何渲染的模板中

考虑到以上几点,您可以构造如下内容:
app.use(function(res, req, next) {
  res.locals.isAuthenticated = typeof(req.user) !== 'undefined';
  next();
});
然后当你的路由调用res.render时,你提供你的额外的模板变量。例如:
app.get('/about', function(res, req) {
  res.render('about', { 'testValue': 14} );
});

你的模板可以访问isAuthenticatedtestValue

我建议你在路由处理程序之前、护照处理程序之后放一些中间件。

app.use(function(req, res, next) {
    // Create a `context` object for use in any view.
    // This allows the context to grow without impacting too much.
    req.context = {};
    // Assign your flag for authenticated.
    req.context.isAuthenticated = typeof req.user !== 'undefined';
    // Let the next middleware function perform it's processing.
    next();
});

然后你可以用上下文渲染每个视图。

app.use('/', function(req, res) {
    res.render('index', req.context); // Context is passed to view for usage.
});

您可以像这里已经提到的那样做,但是在这种情况下,您将完全检查每个请求。可能有些页面不需要任何身份验证此时你需要写一些语句跳过该页面的身份验证或者你可以这样写:

function checkUser(req, res, next) {
    req.userAuth = (req.user !== undefined);
    next();
}
app.post("settings", checkUser, doSomething);
app.post("administration", checkUser, doSomething);
app.post("index", doSomething); // Doesn't require any authentification

或者你可以直接重定向用户

function checkUser(req, res, next) {
    if (req.user === undefined) {
        res.redirect("/login"); // res.render
    }
    else {
        next();
    }
}