Express+EJS应用部署Vercel成功后出现Internal Server Error
问题:Express+EJS应用部署Vercel后显示Internal Server Error,本地运行正常
我已经把搭载EJS模板引擎的Express应用部署到Vercel,但访问Vercel提供的链接时,浏览器显示Internal Server Error。本地通过npm run dev运行完全正常,已经配置了对应的package.json、index.js和vercel.json,尝试过Vercel官方的Express部署方案后问题仍未解决。
项目结构:
配置文件详情
package.json
{ "name": "templates", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node api/index.js", "start:dev": "PORT=3000 node server.js", "dev": "nodemon api/index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "body-parser": "^1.20.2", "ejs": "^3.1.9", "express": "^4.18.2", "express-ejs-layouts": "^2.5.1", "zod": "^3.22.4" }, "devDependencies": { "nodemon": "^3.1.0" } }
index.js(位于api目录下)
const express = require("express"); const expressLayouts = require("express-ejs-layouts"); const { formValidationSchema } = require("../schemas/formvalidation"); const app = express(); const PORT = 8080; app.use(express.static(__dirname + "../public")); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.set("views", "./views"); app.use(expressLayouts); app.set("layout", "../views/layouts/layout"); app.set("view engine", "ejs"); app.get("/", async function (req, res) { res.render("index", { title: "Welcome to my portfolio!", // Other data }); });
vercel.json
{ "version": 2, "rewrites": [{ "source": "/(.*)", "destination": "/api" }] }
排查与修复步骤
修正路径拼接问题
直接用字符串拼接路径容易出错,改用path模块处理:const path = require("path"); // 修正静态资源路径 app.use(express.static(path.join(__dirname, "../public"))); // 修正视图根目录路径 app.set("views", path.join(__dirname, "../views")); // 修正布局路径(基于views根目录) app.set("layout", "./layouts/layout");适配Vercel端口规则
Vercel会自动分配端口,不能硬编码固定端口,添加监听逻辑:const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });更新vercel.json配置
明确指定构建规则和入口文件:{ "version": 2, "builds": [ { "src": "api/index.js", "use": "@vercel/node" } ], "rewrites": [ { "source": "/(.*)", "destination": "/api/index.js" } ] }检查依赖与日志
- 本地执行
npm install确保依赖完整后重新推送代码 - 登录Vercel控制台查看项目Logs标签,获取具体错误信息(如模块缺失、路径错误等)
- 本地执行
内容的提问来源于stack exchange,提问作者Omar Waqar
相关产品推荐
相关产品推荐

