我刚刚在 vercel 上部署了我的 Express 应用程序,该应用程序部署时没有任何错误,但现在当我转到 vercel 提供的链接时,我在浏览器上看到内部服务器错误。
我也在我的 Express 应用程序中使用 EJS 模板引擎。 这是我的项目的文件夹结构。
这是我项目的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"
}
}
我使用 npm run dev 在本地运行项目,并且运行良好。
这是index.js文件代码
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" }]
}
我尝试了官方的 next js 提供的在 vercel 上使用 Express 应用程序的方法,但仍然失败
https://vercel.com/guides/using-express-with-vercel
您需要从
app
文件导出 index.js
。尝试放置以下内容
代码位于 index.js
文件末尾。
module.exports = app;
更新您的
vercel.json
,如下所示。
{
"version": 2,
"name": "templates",
"builds": [{
"src": "api/index.js",
"use": "@vercel/node"
}],
"routes": [{
"src": "/(.*)",
"dest": "/api/index.js"
}]
}