简体   繁体   中英

Expressjs remove static folder

I have nodejs webpage and i am using expressjs. I have few static folders and with user log out i have to remove some of them. Below is how i add static folder, i am not using any options maybe that is the problem.

app.use(express.static(__dirname + '/public'));

And i need something like below:

app.use(express.removeStatic(__dirname + '/public'));

or

app.use(express.static(__dirname + '/public',{vissible: false}));

As described here the express.static middleware is based on serve-static . There is no way of removing already loaded middleware (static files).

What I would suggest is creating your own serve-static middleware. You can use this as reference then just load the session middleware before the serve-static middleware then add an option that checks if the session data is available, if not then don't serve.

The basic idea is something like:

  return function serveStatic(req, res, next) {
    if (req.method !== 'GET' && req.method !== 'HEAD') {
      return next()
    }
    // add this
    if (req.session.loggedIn === false) {
      return next()
    }

Example

I have copied the serve-static code and added a condition to it, you can get it here .

  • Download it and save it as serve-static.js .
  • Include it in your expressjs project.
  • Modify to your use case.
  • Beware untested code.

Usage

var static = require('./serve-static')
// session middleware here
app.use(static(__dirname + '/public'));

This should only serve the static files when the req.session.loggedIn is true .

Of course you can change the condition to anything you want like:

if (req.session && req.session.ANYTHING_I_WANT === false && !!someMore)  {
  // skip all the code below (will not serve)
  return next()
}

The condition can be found on line 64 of my serve-static gist.

Remember to add the session middleware before using the static middleware.

You can't remove static folders from express. What you can do is use res.sendFile to send a file as the response. For example:

app.get('public/:filename', function(req, res){
  if(user.loggedIn) {
    res.sendFile(req.params[:filename]);
  } else {
    res.status(402).send("Log in to access file");
  }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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