ExpressJS中Cannot read properties of undefined (reading 'use')错误解决
解决ExpressJS中"Cannot read properties of undefined (reading 'use')"错误
问题场景
终端提示错误Cannot read properties of undefined (reading 'use'),问题指向app>router>routers.js的路由引入环节。
错误原因分析
- 子路由导出名称不匹配:以
Team.js为例,文件中导出的是projectRouters,但routers.js中尝试导入的是teamRouters,导致该变量为undefined,调用router.use()时传入无效参数触发错误。 - Server.js路由挂载逻辑错误:错误将路由挂载代码放在错误处理中间件内部,且错误处理中间件的位置不符合Express规范,同时可能存在
AllRouters未正确导入的问题。
修复步骤
1. 修正子路由文件的导出名称
确保每个子路由文件的导出名称与routers.js中的导入名称一致:
Team.js修正后代码:
const router = require("express").Router(); // 你的业务代码... module.exports = { teamRouters: router };
- 同理,
Project.js导出projectRouters、Auth.js导出authRouters、User.js导出userRouters,保持导入导出名称一一对应。
2. 修正Server.js的路由挂载与错误处理逻辑
- 首先确保正确导入
AllRouters:
const { AllRouters } = require("./app/router/routers.js"); // 根据实际项目路径调整
- 调整
createRoutes方法,将路由挂载放在错误处理中间件之前,错误处理中间件仅负责错误处理:
createRoutes() { // 根路径路由 this.#app.get("/", (req, res, next) => { return res.json({ message: "Welcome to my app" }); }); // 挂载所有子路由 this.#app.use(AllRouters); // 错误处理中间件(必须放在所有路由之后) this.#app.use((error, req, res, next) => { res.status(error.status || 500).json({ message: error.message || "Internal Server Error" }); }); }
3. 优化routers.js冗余代码
当前代码中const app = express();未被使用,可删除以精简代码:
const express = require("express"); const router = express.Router(); const { authRouters } = require("./Auth"); const { projectRouters } = require("./Project"); const { teamRouters } = require("./Team"); const { userRouters } = require("./User"); router.use("/project", projectRouters); router.use("/team", teamRouters); router.use("/user", userRouters); router.use("/Auth", authRouters); module.exports = { AllRouters: router };
内容的提问来源于stack exchange,提问作者Sara Asefi
相关产品推荐
相关产品推荐

