在路由器Express之间切换

时间:2017-05-02 15:02:12

标签: node.js express

我希望显示一个完全不同于任意值的网站。

假设我有两个路由器

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

我不知道我怎么能这样做。我将有很多路线(router.getrouter.post)我不想在每条路线上检查

由于

3 个答案:

答案 0 :(得分:1)

只需回拨路由器:

app.use((req, res, next) => {
    if(Math.random() > 0.5) {
        return router1(req, res, next)
    } else {
        return router2(req, res, next)
    }
})

答案 1 :(得分:0)

为什么不呢?

if(Math.random() > 0.5) {
    app.use(router1);
} else {
    app.use(router2);
}

答案 2 :(得分:0)

这也可以通过使用.next('router')方法来完成。

以下是一个例子:

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')基本上会跳到下一个路由器对象(已在app.use行中提及,如果仅使用next(),则继续使用当前的路由器方法。