Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

97
Visualizações
Switch between routers Express

I want to display a website completely different in function of an arbitrary value.

Let's say I have two routers

const express = require('express');
const app = express();
const router1 = express.Router();
router1.get('/', (req, res, next) => res.json({message: 'I am the router1'}))
const router2 = express.Router();
router2.get('/', (req, res, next) => res.json({message: 'I am the router2'}))
app.use((req, res, next) => {
    if(Math.random() > 0.5) {
        // Use router1
    } else {
        // Use router2
    }
})

I have no idea how I can do that. I will have a lots of routes (router.get, router.post) I don't want to check that on each route

Thanks

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

This can also be done by usage of .next('router') method.

Here is an example:

const router1 = express.Router();

router1.use((req, res, next) => { 

  console.log("This gets called everytime!");

  if(Math.random() > 0.5) 
    next('router');//skip to next router object
  else
    next();//continue with current router
});

router1.get('/',(req, res, next) => {
  console.log("Continuing with current router");
  res.send("Continuing with current router");
});


const router2 = express.Router();

router2.get('/', (req, res, next) => {
  console.log("Skipped Router 1, continuing with router 2");
  res.send("Skipped Router 1, continuing with router 2");
});

//binding both routers here
app.use("*", router1, router2);

.next('router') basically skips to next router object, which has been mentioned in the app.use line, if only next() is used then it continues with current router methods.

about 4 years ago · Santiago Trujillo Relatório

0

Just return a call to the router:

app.use((req, res, next) => {
    if(Math.random() > 0.5) {
        return router1(req, res, next)
    } else {
        return router2(req, res, next)
    }
})
about 4 years ago · Santiago Trujillo Relatório

0

Why not just?

if(Math.random() > 0.5) {
    app.use(router1);
} else {
    app.use(router2);
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda