Node.js表示嵌套的资源

我想嵌套像下面的资源。

/// fileA.js app.use('/dashboards/:dashboard_id/teams', teams); [...] ///teams.js router.get('/', function(req, res, next) { [...] } 

但是我不能在团队中获得req.params [“dashboard_id”]参数,因为它似乎已经被参数值替代了。 我试图通过调用一个中间函数来绕过这个问题,并通过某个地方的参数,但我不知道在哪里…你有答案吗? 谢谢你,佛朗哥

       

网上收集的解决方案 "Node.js表示嵌套的资源"

你可以试试这个解决scheme:

 //declare a function that will pass primary router's params to the request var passPrimaryParams = function(req, res, next) { req.primaryParams = req.params; next(); } /// fileA.js app.use('/dashboards/:dashboard_id/teams', passPrimaryParams); app.use('/dashboards/:dashboard_id/teams', teams); ///teams.js router.get('/', function(req, res, next) { var dashboardId = req.primaryParams['dashboard_id']; //should work now //here you may also use req.params -- current router's params } 

在撰写本文时使用Express 4.0.0或以上版本:

为了让路由器了解variables的嵌套资源,您需要使用app.use为每个基本path创build并绑定一个新的路由器。

 //creates a new router var dashboardRouter = express.router(); //bind your route dashboardRouter.get("/:dashboard_id/teams", teams); //bind to application router app.use('/dashboards', dashboardRouter); 

这样,Express将看到path的第一部分,然后转到/dashboards路线,该路线包含:dashboard_id/teamspath。

您可以在这里使用mergeParams选项

 // fileA.js app.use('/dashboards/:dashboard_id/teams', teams); // teams.js const router = express.Router({ mergeParams: true }) router.get('/', function(req, res, next) { // you will have access to req.params.dashboard_id here } 

您也可以看到这个答案: rest与Express.js嵌套路由器