为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

牛魔王的故事 2021-06-30 09:11:17
我的其中一台路由器中有以下 router.use 调用router.use("/:collection/", (req) => {    return require(`./${req.params.collection}`);});在这个例子中调用,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请求它会在控制台中写入以下内容:123test我会得到回应:{msg:"hi"}相反,控制台只得到:123写了,没有回应。看来 router.get在 example.js 中从未被调用,有人能告诉我为什么吗?
查看完整描述

1 回答

?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

我修复了它,而不是


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();

});


查看完整回答
反对 回复 2021-07-08
  • 1 回答
  • 0 关注
  • 136 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信