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
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.
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)
}
})
Why not just?
if(Math.random() > 0.5) {
app.use(router1);
} else {
app.use(router2);
}