简体   繁体   English

一些 Express.Router() 路由不执行中间件功能

[英]Some Express.Router() routes do not execute middleware function

I'm trying to wrap my head around my implementation of express.router() not triggering of the middleware function assigned to it.我试图围绕我的 express.router() 实现而不是触发分配给它的中间件功能。 I wrote a pretty big app and trying to add a few more endpoints to my path, but for some reason the 9th route gets loaded but does not trigger the function.我编写了一个相当大的应用程序并尝试向我的路径添加更多端点,但由于某种原因,第 9 条路由被加载但没有触发该功能。

app.js应用程序.js

server.use(cors());
server.use(function (req, res, next) {
  next();
});
server.use("/", express.static("./assets"));
server.use("/api", api);
server.use("/debug", debug);
server.use("/config", config);
server.use("/control", control);
server.use("/tools", files);

And this is where I declared my routes with the respective functions.这就是我用各自的功能声明我的路线的地方。

router.get("/teams", onGetTeams);
router.get("/players", onGetPlayers);
router.get("/achievements", getTop3);
router.get("/xpression", onXprPayload);
router.get("/snapshot", onRequestSnapshot);
router.get("/round-timeline", onRequestTimelinePayload);
router.get("/:half", onRequestHalf);
router.get("/dashboard-message", onSetDashboardMessage);
router.get("/get-match-odds", getTeamOdds);
function getTeamOdds(req, res) {
  console.log("Sent odds");
  res.json(odds);
  res.end();
}

When I make the request for the last route, the function does not get executed, and I get back a 200 response.当我请求最后一条路由时,该函数没有被执行,我得到了一个 200 响应。

Is there something big I'm missing?我错过了什么大事吗?

Thank you !谢谢 !

Your route definition here:您的路线定义在这里:

router.get("/:half", onRequestHalf);

is a wildcard route that matches ALL routes so none of the routes after it will get called unless that specific route calls next() to continue routing.是匹配所有路由的通配符路由,因此除非该特定路由调用next()以继续路由,否则不会调用它之​​后的任何路由。

Top level wildcard routes are problematic for this reason.由于这个原因,顶级通配符路由存在问题。 I would suggest avoiding them.我建议避免它们。 There are temporary work-arounds like moving their definition to be the last top level route definition, but they can still be limiting for defining future routes because they are so greedy.有一些临时的解决方法,比如将它们的定义移动到最后一个顶级路由定义,但它们仍然可以限制定义未来的路由,因为它们太贪婪了。

My recommendation would be to not make it a top level route:我的建议是不要让它成为顶级路线:

router.get("/half/:half", onRequestHalf);

So, it won't conflict with the other top level routes and it essentially has it's own URL scope all to itself.因此,它不会与其他顶级路由冲突,并且它本质上拥有自己的 URL 范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM