简体   繁体   中英

Node express change static folder on a user by user basis

Is it possible to do something like this with node and express middleware?

app.use('/',express.static('public'))

app.get('/public', function() {
  app.use('/',express.static('public'))
})
app.get('/public2', function() {
  app.use('/',express.static('public2'))
})

What i'm trying to accomplish is allowing users to have their own "public" directories to serve static files. the directory structure would be something like /user/< hash >

Think I have a solution for you!

app.get('/:user', function(req, res, next) {
    app.use('/', express.static(path.join(__dirname, 'public/' + req.params.user)));
    res.send('');
});

To explain, imagine the two files at the paths:

/__dirname/public/user1/userdata.text

/__dirname/public/user2/userdata.text

By visiting the following two URLs:

http://localhost:3000/user1/userdata.txt

http://localhost:3000/user2/userdata.txt

You'd be requesting those two different files respectively. If the file doesn't exist, it throws a 404 like you'd expect!

Hope this helps.

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