You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 15:04:33