在Vercel部署Node.js+Express+TypeScript应用遇404错误求解决方案
解决Vercel部署Node.js/Express TypeScript应用的404错误
问题核心
你的配置存在3个关键问题:
vercel.json路由规则错误,dest指向的根路径无对应处理文件package.json缺少TypeScript编译命令,且main字段指向错误- 未配置
tsconfig.json(TypeScript项目必需)
正确部署步骤
1. 修正vercel.json配置
将路由的dest直接指向TS入口文件,确保请求能被正确转发:
{ "version": 2, "builds": [ { "src": "src/index.ts", "use": "@vercel/node" } ], "routes": [ { "src": "/(.*)", "dest": "src/index.ts" } ] }
2. 更新package.json
调整入口指向、添加编译命令、适配生产环境启动逻辑:
{ "name": "backend", "version": "1.0.0", "description": "", "main": "src/index.ts", "scripts": { "start": "ts-node src/index.ts", "build": "tsc", "dev": "nodemon", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@types/body-parser": "^1.19.2", "@types/compression": "^1.7.2", "@types/express": "^4.17.17", "@types/jsonwebtoken": "^9.0.2", "@types/nodemailer": "^6.4.9", "nodemon": "^3.0.1", "ts-node": "^10.9.1", "tsconfig-paths": "^4.2.0", "typescript": "^5.2.2" }, "dependencies": { "@types/node": "^20.5.7", "body-parser": "^1.20.2", "compression": "^1.7.4", "dotenv": "^16.3.1", "express": "^4.18.2", "helmet": "^7.0.0", "jsonwebtoken": "^9.0.2", "mongoose": "^7.5.0", "nodemailer": "^6.9.4" } }
3. 添加tsconfig.json配置
这是TypeScript编译的核心配置,确保代码能正确转译为Node.js可执行的JS:
{ "compilerOptions": { "target": "ES2020", "module": "commonjs", "outDir": "./dist", "rootDir": "./src", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["node_modules"] }
如果选择用编译后的JS文件部署,需同步修改vercel.json:
{ "version": 2, "builds": [ { "src": "dist/index.js", "use": "@vercel/node" } ], "routes": [ { "src": "/(.*)", "dest": "dist/index.js" } ] }
4. 修正Express端口监听逻辑
Vercel会分配动态端口,必须用环境变量获取:
import express from 'express'; const app = express(); const PORT = process.env.PORT || 3000; // 示例路由 app.get('/', (req, res) => { res.send('服务运行正常'); }); app.listen(PORT, () => { console.log(`服务启动于端口 ${PORT}`); });
5. 重新部署
将所有修改推送到Git仓库,在Vercel后台触发重新部署,等待构建完成即可。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

