Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
Cambiar entre enrutadores Express

Quiero mostrar un sitio web completamente diferente en función de un valor arbitrario.

Digamos que tengo dos enrutadores

 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 } })

No tengo idea de cómo puedo hacer eso. Tendré muchas rutas ( router.get , router.post ) No quiero verificar eso en cada ruta

Gracias

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Esto también se puede hacer mediante el uso del .next('router') .

Aquí hay un ejemplo:

 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') básicamente salta al siguiente objeto de enrutador, que se ha mencionado en la línea app.use , si solo se usa next() , entonces continúa con los métodos de enrutador actuales.

over 4 years ago · Santiago Trujillo Report

0

Simplemente devuelva una llamada al enrutador:

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

0

¿Por qué no solo?

 if(Math.random() > 0.5) { app.use(router1); } else { app.use(router2); }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!