Express子路由失效咨询:/api/students等端点无法正常访问
问题排查与修复
你的路由配置存在两个核心问题,导致子端点无法正常访问:
1. 循环路由挂载(导致/api/api可访问)
在./src/routes/index.ts中,你写了一行:
routes.use('/api', routes);
这是循环挂载——把当前的routes路由器挂载到自身的/api路径下,会导致路由规则混乱,不仅让/api/api能被访问,还会干扰后续/students和/teachers路由的匹配逻辑。
修复:直接删除这行代码
2. 子路由路径重复定义
在./src/routes/api/students.ts中,你定义的路由是:
students.get('/students', (req, res) => { res.send('connected to the server. students route'); });
而在index.ts中,你已经将students路由器挂载到/students路径下:
routes.use('/students', students);
这意味着实际的匹配路径会变成/api/students/students,而你期望的是/api/students,自然无法命中。
修复:将子路由的路径改为根路径/
修改后的代码示例:
./src/routes/index.ts
import express from 'express'; import students from './api/students'; import teachers from './api/teachers'; const routes = express.Router(); // 主API根路径 routes.get('/', (req, res) => { res.send('connected to the server. main api route'); }); // 挂载子路由,删除循环挂载的代码 routes.use('/students', students); routes.use('/teachers', teachers); export default routes;
./src/routes/api/students.ts
import express from 'express'; const students = express.Router(); // 改为根路径,对应挂载后的/api/students students.get('/', (req, res) => { res.send('connected to the server. students route'); }); export default students;
验证修复结果
修改完成后重启服务,以下端点即可正常访问:
GET http://127.0.0.1:3000/api→ 返回主API路由内容GET http://127.0.0.1:3000/api/students→ 返回学生路由内容GET http://127.0.0.1:3000/api/teachers→ 返回教师路由内容(需确保teachers.ts做了同样的路径修改)
内容的提问来源于stack exchange,提问作者Ahmed
相关产品推荐
相关产品推荐

