牛魔王的故事
2021-06-30 09:11:17
我的其中一臺路由器中有以下 router.use 調(diào)用router.use("/:collection/", (req) => { return require(`./${req.params.collection}`);});在這個例子中調(diào)用,example.jsexample.js 如下:const header = require("../../header"); //gets our header that declares everythingconst router = header.express.Router(); //makes our router for collections requestsconsole.log("123");///The Following is when a name is requestedrouter.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請求它會在控制臺中寫入以下內(nèi)容:123test我會得到回應(yīng):{msg:"hi"}相反,控制臺只得到:123寫了,沒有回應(yīng)。看來 router.get在 example.js 中從未被調(diào)用,有人能告訴我為什么嗎?
1 回答

侃侃爾雅
TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個贊
我修復(fù)了它,而不是
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();
});
添加回答
舉報(bào)
0/150
提交
取消