Express Router路由异常:/api/get类路径未命中指定路由
问题根源及修复方案
1. 修正server.js中的路由挂载方式
你当前用app.use("/api/*", apiRouter)挂载路由,这会导致Express对请求路径的解析异常——它会把/api/之后的全部内容作为通配符匹配项,传递给Router时丢失了正确的子路径信息(从你的控制台输出能看到req.path为空或异常)。
修复代码:
// 替换原有的挂载语句 app.use("/api", apiRouter);
2. 精简并修正router.js中的路由定义
因为Router已经挂载在/api路径下,所以Router内部的路由路径是相对于/api的子路径,不需要再包含/api前缀。同时清理冗余的重复路由,保留有效定义即可:
修正后的router.js:
const express = require("express"); const router = express.Router(); // 匹配 GET /api/get router.get("/get", (req, res) => { console.log("fallen into the get3"); }); // 匹配 GET /api/get/blah 这类带参数的路径 router.get("/get/:dictionaryId", (req, res) => { console.log("fallen into the get"); }); // 兜底路由 router.get("*", (req, res) => { console.log("falling into the catch all api route"); console.log(`API request passed through: ${req.originalUrl}`); console.log(`API request passed through: ${req.path}`); }); module.exports = router;
验证效果
- 访问
http://localhost:5000/api/get时,会命中/get路由,控制台输出fallen into the get3 - 访问
http://localhost:5000/api/get/blah时,会命中/get/:dictionaryId路由,控制台输出fallen into the get
内容的提问来源于stack exchange,提问作者Richard Whitehouse
相关产品推荐
相关产品推荐

