如何使用Express和Nodejs保护静态路由

Chr*_*ian 6 javascript node.js express

我使用Node(最新版本)+ Express,也是最新版本.我有2个文件夹,公共和安全.只有在登录后才能访问受保护的文件夹.

我自己创建了一个登录系统,现在我想知道如何保证到这个"安全文件夹"的路由.

我很想设置一个静态路由到我的"安全"文件夹(就像我对公共文件夹一样),然后检查用户是否已登录,但它不起作用.

这是我认为应该工作的......

(...)
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'secured')));
(...)

function requireLogin(req, res, next) {
  if (req.session.loggedIn) {
    next(); // allow the next route to run
  } else {
    // require the user to log in
    res.redirect("/login"); 
  }
}

app.all("/secured/*", requireLogin, function(req, res, next) {
  next(); 

});
Run Code Online (Sandbox Code Playgroud)

zem*_*rco 13

在单独的路径上为您的私有静态指定不同的文件夹

app.use(express.static(path.join(__dirname, 'public')));
app.use('/private', express.static(path.join(__dirname, 'private')));
Run Code Online (Sandbox Code Playgroud)

然后,您可以在每个请求上使用您的中间件

app.all('/private/*', function(req, res, next) {
  if (req.session.loggedIn) {
    next(); // allow the next route to run
  } else {
    // require the user to log in
    res.redirect("/login"); 
  }
})
Run Code Online (Sandbox Code Playgroud)

  • 看起来 app.all('/private/*') 只匹配私有文件夹,但如果用户输入 /private/index.html,它不匹配此规则.. (2认同)
  • 好的,我现在就开始工作了.诀窍是在定义到私有文件夹的静态路由之前放置app.all(/ private/*).. 对不起,我是节点新手,但今天我学到了很多东西.谢谢! (2认同)

Pas*_*cle 5

在你的第一个 app.use 之前,

添加类似的东西

app.use(function(req, res, next) {
  if (req.url.match(/^\/secured\//)) {
    return requireLogin(req, res, next);
  }
  next();
})
Run Code Online (Sandbox Code Playgroud)