【问题标题】:How do Allow only Admins to have access to the Admin page in Nodejs `AdminBro`如何仅允许管理员访问 Nodejs `AdminBro` 中的管理页面
【发布时间】:2021-09-07 00:45:15
【问题描述】:

如何只允许管理员访问AdminBro 中的管理员页面? Nodejs

我想要的只是让管理员可以访问 adminBro 页面,是否有任何特定方法可以完成此操作?

我在我的 app.js 文件中执行了此操作,但它不起作用

app.get("/admin", function (req, res, next) {
  res.locals.login = req.user;
  if (res.locals.login.roles == "admin") {
     app.use("/admin", adminRouter);
  } else {
    res.redirect("/");
 }
});

【问题讨论】:

    标签: node.js express admin-bro


    【解决方案1】:

    您不能在app.get 中使用新的app.use,因为(req, res, next) 已被使用。您有两个选择:

    1. if 条件正文中的路线
    if (res.locals.login.roles === 'admin') {
       // your admin route logic
       res.send('admin page')
    } else {
      res.redirect('/')
    }
    
    1. 我习惯使用这样的小型中间件功能:
    const isAdmin = (req, res, next) => {
      if (req.user.roles === 'admin') {
        return next();
      }
      res.redirect('/');
    };
    

    然后你以这种方式在任何路线中使用它:

    app.get('/admin', isAdmin, adminRouter)
    

    【讨论】:

    • 非常感谢,中间件解决方案正是我一直在寻找的,我按照您的建议做了,而且效果很好。 @Fide
    猜你喜欢
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    相关资源
    最近更新 更多