Express嵌套路由器不调用子功能

时间:2019-06-19 20:52:39

标签: javascript node.js express

我有以下路由器。在我的一个路由器中使用呼叫

router.use("/:collection/", (req) => {
    return require(`./${req.params.collection}`);
});

,在此示例中为example.js

example.js如下:

const header = require("../../header"); //gets our header that declares everything

const router = header.express.Router(); //makes our router for collections requests


console.log("123");


///The Following is when a name is requested
router.get("/test", (req, res, next) => {
    console.log("test");
    res.json({msg:"hi"});
    next();
});


module.exports = router; //makes our router avialable

您希望何时:

http://localhost:3000/api/example/test

要求它在控制台中写入以下内容:

123
test

我会得到答复:

{msg:"hi"}

相反,控制台仅显示:

123

书面,没有回应。

似乎

 router.get

从未调用过example.js,有人可以告诉我为什么吗?

1 个答案:

答案 0 :(得分:0)

我修复了它,而不是

router.use("/:collection/", (req) => {
    return require(`./${req.params.collection}`);
});

我使用

router.get("/:collection", (req, res) => {
  //this is my other call that will do stuff in the parent file
  //we don't call next because it is already matched, otherwise we call next
});

router.use("/:collection/", (req, res, next) =>{ //says if it gets here pass on the info
  router.use("/:collection/", require(`./${req.params.collection}`)); //then route
  next();
});