简体   繁体   中英

Making a conditional app.use() with Node and Express?

I would like to be able to set an app.use() path depending on the domain my Node.JS server receives the request as to return one set of files or another. I have tried with the following code, but when testing the files are never returned to the client.

app.use('/scripts', (req, res) => {

    if (req.host == `mysite.com`) {

        express.static(path.resolve(__dirname, 'landing', 'frontend/scripts'));
        
    } else if (req.host == `admin.mysite.com`) {

        express.static(path.resolve(__dirname, 'admin', 'frontend/scripts'));
    }
});

I am using express as a dependancy to try and do this, but no avail, I am willing to try other packages if this can help solve my issue.

Not tested, but I would assume you can keep a reference to each static route and then just forward the requests, don't forget next so that normal 404 can be handled.

eg.

const static1 = express.static(path.resolve(__dirname, 'landing', 'frontend/scripts'));
const static2 = express.static(path.resolve(__dirname, 'admin', 'frontend/scripts'));

app.use('/scripts', (req, res, next) => {
    if (req.hostname == `mysite.com`) {
        static1(req, res, next);       
    } else if (req.hostname == `admin.mysite.com`) {
        static2(req, res, next);
    } else res.end(`host: ${req.hostname} not found`);
});

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