简体   繁体   中英

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. 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.

app.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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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