快速嵌套路由器不调用子功能

我的其中一台路由器中有以下 router.use 调用


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 中从未被调用,有人能告诉我为什么吗?


牛魔王的故事
浏览 150回答 1
1回答

侃侃尔雅

我修复了它,而不是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();});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript