How to secure a static route with Express and Nodejs

后端 未结 2 450
盖世英雄少女心
盖世英雄少女心 2021-02-02 02:36

I use Node (latest version) + Express, also latest Version. I have 2 folders, public and secured. The secured folder should only be accessible after login.

I\'ve create

相关标签:
2条回答
  • 2021-02-02 03:14

    Specify a different folder for your private statics on a separate route

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

    Then you can use your middleware on each request

    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"); 
      }
    })
    
    0 讨论(0)
  • 2021-02-02 03:16

    before your first app.use,

    add something like

    app.use(function(req, res, next) {
      if (req.url.match(/^\/secured\//)) {
        return requireLogin(req, res, next);
      }
      next();
    })
    
    0 讨论(0)
提交回复
热议问题