简体   繁体   中英

Set express.static directory dynamically

I want to set root directory of exress.static in a way that request from a subdomain will have separate root folder.

I have a site with multiple subdomain, and the structure is a following

index.js
public/
-- site1
-- site2
-- site3

i want to set public/site1 as static folder when request is from site1.mydomain.com and site2.mydomain.com should not be able to get files from public/site1 directory.

I have tried this:

app.use ((req, res, next) => {
  let hostName = req.headers.host;
  let options = domainMap[hostName];

  req.app.use (
    express.static (path.join (__dirname, 'public', options.publicDir))
  );

  next ();
});

domainMap holds the following object:

{
    site1:{
         publicDir:'site1',
    },
    site2:{
         publicDir:'site2',
    },
    site3:{
         publicDir:'site3',
    }
}

what it does now is it sets the public directory only for the first request, but is there any way to change i dynamically for every request ?

You can generate the desired middleware function dynamically and then call it manually. You don't want to register it with app.use() because then it will be active for all requests. That's why you need to call it manually. Also, express.static() generates a middleware that already calls next() so you don't need to do that either except in cases where you don't call the generated middleware.

app.use ((req, res, next) => {
  let hostName = req.headers.host;
  let options = domainMap[hostName];
  // protect against missing or unexpected hostName
  if (options && options.publicDir) {
      let middleware = express.static(path.join (__dirname, 'public', options.publicDir));
      middleware(req, res, next);
  } else {
      // nothing to do here, keep routing
      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