Node.js/Express中如何高效为特定路由配置认证中间件?
Express 批量配置受保护路由的优化方案
你可以通过以下两种更简洁的方式避免重复添加认证中间件:
方法一:拆分路由组
创建独立的受保护路由实例,给整个路由组统一应用认证中间件,再挂载到主路由上:
import express from "express"; import authenticateUser from "../../Middlewares/auth.js"; import controller from "./controller.js"; const router = express.Router(); // 公开路由 router.get("/searchFor/:term", controller.searchFor); // 初始化受保护路由组并全局应用认证中间件 const protectedRoutes = express.Router(); protectedRoutes.use(authenticateUser); // 受保护路由无需重复添加中间件 protectedRoutes.get("/myList", controller.getMyList); protectedRoutes .route("/myList/:id") .get(controller.isInList) .post(controller.addToList) .delete(controller.removeFromList); // 将受保护路由组挂载到主路由 router.use("/", protectedRoutes);
方法二:按路径前缀批量应用中间件
直接给特定路径前缀的所有路由绑定认证中间件,无需拆分路由:
import express from "express"; import authenticateUser from "../../Middlewares/auth.js"; import controller from "./controller.js"; const router = express.Router(); // 公开路由 router.get("/searchFor/:term", controller.searchFor); // 给所有 `/myList` 开头的路由自动应用认证中间件 router.use("/myList", authenticateUser); // 后续所有 `/myList` 相关路由默认带上认证逻辑 router.get("/myList", controller.getMyList); router .route("/myList/:id") .get(controller.isInList) .post(controller.addToList) .delete(controller.removeFromList);
为什么你之前的写法无效?
router.route() 方法的第一个参数仅支持传入路由路径,不支持直接传递中间件,所以你尝试的 .route("/myList/:id", authenticateUser) 写法不会生效。
内容的提问来源于stack exchange,提问作者Itai Simhony
相关产品推荐
相关产品推荐

