简体   繁体   中英

Express.js trying to set express.static with variables

I have template settings that vary depending on the subdomain I'm using. Therefore I'm trying to find a way to set the express.static dynamically based on the subdomain name I'm using.

When app.use runs, template is undefined. If I run app.use inside app.get it is out of scope. And if I try to run app.use from a function it is also out of scope.

"template" is a variable that I get in app.get it is my subdomain and http request

app.use('/subdomain/:domain/bower',express.static(path.join(__dirname, '/public/' + **template** + '/bower')));

app.get('/subdomain/:domain',function(req,res,next) {    

        get('/stores/template/' + req.params.domain)
        .then(function(body){
          console.log("template: " + body.toString());
            template = body;                
            res.render('store',{store:req.params.domain});  
        });

});

I'm pretty sure it has to do with scopes, but so far I haven't been able to solve it. Any help would be appreciated

Your first app.use() and the express.static() call in it runs when your sever is first starting up. At that point, the template variable does not yet have a value. You can't really do things the way you're trying to do it.

app.get() runs immediately also, but its callback is not called until sometime in the future when an http request matching that route actually arrives. By then, when the template variable gets assigned, it's way too late for it to be useful in your prior app.use() statement.

This would be much easier if your server could just know which sub-domain it was serving when it was originally set up from a configuration file or something like that. If you intend for the same server to serve many sub-domains at once and you want it to serve different files based on the subdomain, then you will have to code completely differently because you can't just use plain route matching like express.static() does since what you really want is sub-domain + route matching which isn't a built-in feature that I'm aware of.

I think if I was trying to solve this, I'd have my first middleware examine the sub-domain of the request and insert it into the front of the URL making a unique pseudo-URL for each sub-domain. Then, you could do normal routing on that pseudo-URL which is what the rest of the middleware and routes will see as the request URL.

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