简体   繁体   中英

Changing static content directory

I am trying to set the express.static path to something different based on a session variable. The relevant code is below.

app.use( '/', function(req, res, next ) {

    if ( req.session.loggedIn ) {
        console.log("loggedIn :  " + req.session.loggedIn);
        app.use('/', express.static(__dirname + '/private'));
        next();
    }
    else {
        console.log("not logged in.");
        app.use('/', express.static(__dirname + '/public'));
        next();
    }

 });

When I start the application, I begin with not having req.session.loggedIn set. So it will use the static content in the /public directory (which contains an angular powered application for public users.) I then do a login (code below)

app.post('/login', function( req, res ) {

    req.session.loggedIn = true;
    var message = {};
    message.success = true;
    message.text = "Logging you in...";
    res.json(message);

});

Which sets the req.session.loggedIn variable to be true. I then hit refresh on the page (and have tried hard refresh, and cache clear/refresh as well). The console.log tells me "loggedIn : true" as expected, however it does NOT load the static content from the /private directory. It instead continues to load from the /public directory.

Can anyone shed light on this issue?

The express.static is just another middleware so you can call it directly with the request and response parameters. Instead of adding it to the '/' route directly you could wrap it in another middleware like this:

var public_pages = express.static(__dirname + '/public');
var private_pages = express.static(__dirname + '/private');

app.use('/', function(req, res, next) {
    if(req.session.loggedIn == 1) {
        private_pages(req, res, next);
    } else {
        public_pages(req, res, next);
    }
});

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