Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

146
Vistas
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.

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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`);
});
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos