Express路由匹配异常:/notification/group端点错误触发getNotificationByIdController
Express路由匹配异常:/notification/group端点错误触发getNotificationByIdController
嘿,我一眼就发现问题出在哪啦!
这是Express路由匹配机制导致的——Express会按照你定义路由的顺序来匹配请求路径。你现在先定义了带动态参数的/notification/:notificationId路由,当请求/notification/group时,Express会把group当成:notificationId的参数值,直接匹配到前面那个动态路由,所以才会错误触发getNotificationByIdController,而不是你期望的getNotificationGroupsController。
解决方法很简单,只需要把静态路径的路由(也就是/notification/group)放到动态参数路由的前面就可以了。这样Express会先检查请求路径是否匹配静态路由,只有不匹配的时候才会去匹配动态参数路由。
修改后的代码如下:
import express from "express"; import { isAdmin } from "../middlewares/auth.middleware"; import notificationControllers from "../controllers/notification.controller"; const adminRouter = express.Router(); // 先定义静态路由:通知分组相关 adminRouter .route("/notification/group") .post(isAdmin, notificationControllers.createNotificationGroupController) .get(isAdmin, notificationControllers.getNotificationGroupsController); // 再定义动态参数路由:单个通知相关 adminRouter .route("/notification/:notificationId") .put(isAdmin, notificationControllers.updateNotificationController) .delete(isAdmin, notificationControllers.deleteNotificationController) .get(isAdmin, notificationControllers.getNotificationByIdController); export default adminRouter;
这样调整之后,当你请求GET /notification/group时,就会正确触发getNotificationGroupsController啦!
备注:内容来源于stack exchange,提问作者rr ss
相关产品推荐
相关产品推荐

