TypeScript版Express RESTful API路由未注册问题求助
Express-TypeScript服务器启动正常但请求挂起,路由失效问题
我为应用创建了一个简易REST API,最初用JavaScript编写时一切正常。切换到TypeScript后,完成类型调整并添加tsconfig配置文件后,Express-TypeScript服务器能正常启动,但用HTTP客户端测试API时请求出现挂起,就像Express没注册任何路由一样。我尝试把路由直接定义在index.ts文件中时功能正常,推测问题出在createServer.ts辅助函数里,求帮忙分析原因。
相关代码文件
createServer.ts
import express, { Application } from "express"; import bodyParser from "body-parser"; import cookieParser from "cookie-parser"; import validateToken from "../middleware/validateToken"; import cors from "cors"; // routes import user from "../routes/user"; import note from "../routes/note"; import speechRecognition from "../routes/speechRecognition"; cors({ origin: "http://localhost:5000", credentials: true }); function createServer(): Application { const app = express(); app.use(cors); app.use(express.json()); app.use( express.urlencoded({ extended: true, }) ); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: false })); app.use( validateToken.unless({ path: [ { url: "/user", method: "POST" }, "/user/authenticate", "/user/refresh-token", ], }) ); app.use("/user", user); app.use("/note", note); app.use("/api", speechRecognition); return app; } export default createServer;
index.ts
import { path } from "app-root-path"; import { Port } from "./types/Port"; import { Application } from "express"; // env import { config } from "dotenv"; config({ path: `${path}/../.env` }); // express import createServer from "../server/utils/createServer"; // db connection import { dbConnection } from "../server/db/connection"; dbConnection(process.env.DB_URI as string); const app: Application = createServer(); const port: Port = process.env.PORT || 3000; app.listen(port, () => console.log(`Server is running on port: ${port}`));
tsconfig.json
{ "compilerOptions": { "esModuleInterop": true, "moduleResolution": "node" } }
package.json 脚本
"server": "ts-node-dev index.ts",
问题原因及修复方案
核心问题:CORS中间件使用错误
你在createServer.ts里犯了一个关键错误:
- 单独调用
cors({ origin: "http://localhost:5000", credentials: true })却没有保存返回的中间件函数 - 后续
app.use(cors)传入的是cors模块本身,而非配置后生成的中间件函数,导致Express无法正确处理请求,最终造成请求挂起
修复步骤
修改createServer.ts中的CORS相关代码:
- 删除单独的
cors({ origin: "http://localhost:5000", credentials: true });调用 - 将
app.use(cors);替换为app.use(cors({ origin: "http://localhost:5000", credentials: true }));
修复后的关键代码片段:
function createServer(): Application { const app = express(); // 直接传入配置后的cors中间件 app.use(cors({ origin: "http://localhost:5000", credentials: true })); app.use(express.json()); // ... 其他中间件和路由代码保持不变 }
额外优化建议
- 你同时使用了
express.urlencoded和bodyParser.urlencoded,二者功能重复,Express内置的express.urlencoded已足够,建议移除bodyParser.urlencoded的调用 - 确认
validateToken中间件内部逻辑正常(比如未遗漏next()调用),若中间件卡住也会导致请求挂起,但根据你的测试情况,核心问题还是CORS的使用错误
内容的提问来源于stack exchange,提问作者wszmelczerczyk
相关产品推荐
相关产品推荐

