You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express.js+MongoDB+EJS项目部署至Vercel后出现404错误的求助

Express.js+MongoDB+EJS项目部署至Vercel后出现404错误的求助

Hey there, let's troubleshoot why your Express+EJS app is hitting a 404 after deploying to Vercel. I've gone through your project setup, and here are the key fixes you need to implement:

1. Fix Your vercel.json Configuration

Your current Vercel config points to db.js as the source, but that file starts a standalone server—which doesn't play nice with Vercel's serverless environment. Instead, we need to route all requests directly to your Express app instance in app.js. Update your vercel.json to this:

{
  "version": 2,
  "builds": [
    {
      "src": "app.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/app.js"
    }
  ]
}

This tells Vercel to use your Express app as the request handler instead of a self-managed server.

2. Refactor Database Connection for Serverless Environment

Vercel runs code in ephemeral serverless functions, so you can't keep a persistent server running like you do locally. We need to separate database connection logic from server startup:

Update db.js

Rewrite it to export connection functions instead of starting the server:

let mongodb = require("mongodb");
const dotenv = require("dotenv");
dotenv.config();

let db;

// Async function to connect to MongoDB
async function connectDB() {
  try {
    const client = await mongodb.connect(
      process.env.CONNECTIONSTRING,
      { useNewUrlParser: true, useUnifiedTopology: true }
    );
    db = client.db();
    console.log("Connected to MongoDB successfully");
  } catch (err) {
    console.error("MongoDB connection error:", err);
    throw err;
  }
}

// Function to get the DB instance
function getDB() {
  if (!db) {
    throw new Error("Database not connected");
  }
  return db;
}

module.exports = { connectDB, getDB };

Update app.js

Move server startup logic to only run in local development, and ensure the DB connects before handling requests:

let express = require("express");
let app = express();
let session = require("express-session");
let flash = require("connect-flash");
const formidableMiddleware = require("express-formidable-v2");
let { connectDB } = require("./db");
let router = require("./router");

// Configure EJS
app.set("views", "./views");
app.set("view engine", "ejs");

// Session configuration (add secure cookie for production)
let sessionOptions = session({
  secret: process.env.SESSION_SECRET || "your-secret-key-here",
  resave: false,
  saveUninitialized: false,
  cookie: {
    maxAge: 100 * 60 * 60 * 24,
    httpOnly: true,
    secure: process.env.NODE_ENV === "production" // Critical for production security
  },
});

// Middleware setup
app.use(flash());
app.use(sessionOptions);
app.use(express.urlencoded({ limit: "25mb", extended: true }));
app.use(express.static(__dirname + "/public"));
app.use(express.json({ limit: "25mb" }));
app.use(formidableMiddleware());
app.use("/", router);

// Connect to DB and start server ONLY in local development
if (process.env.NODE_ENV !== "production") {
  connectDB().then(() => {
    let port = process.env.PORT || 3001;
    let server = app.listen(port, () => {
      console.log(`Server running on http://localhost:${port}`);
    });
    server.keepAliveTimeout = 70000;
    server.headersTimeout = 75000;
  });
}

// Export the Express app for Vercel to use
module.exports = app;

3. Adjust package.json Settings

Update the main field and scripts to match the new setup, and upgrade Node to a supported version:

{
  "main": "app.js",
  "engines": {
    "node": "16.x" // 14.x is end-of-life; Vercel recommends newer versions
  },
  "scripts": {
    "start": "NODE_ENV=production node app.js",
    "dev": "nodemon app.js",
    "watch": "nodemon app.js --ignore frontend-js --ignore public/",
    "watch2": "nodemon app.js --ignore frontend-js --ignore public/ && start webpack --watch"
  }
}

4. Configure Vercel Environment Variables

Your local .env file won't be deployed, so add these variables manually in your Vercel project dashboard:

  • CONNECTIONSTRING: Your MongoDB connection string
  • SESSION_SECRET: The secret used for Express sessions
  • Any other environment variables your app relies on

5. Fix File Upload Logic (Critical for Serverless)

Vercel's serverless functions don't support persistent local storage, so your temp-uploads and uploads folders won't work as expected. Modify your image processing logic to directly stream uploaded files to Firebase Storage without saving them to the local filesystem.

6. Verify EJS Render Paths

Double-check that all res.render() calls in router.js use correct relative paths to files in the views folder (e.g., res.render("home") for views/home.ejs).

After making these changes, redeploy your app to Vercel, and the 404 error should be resolved.

备注:内容来源于stack exchange,提问作者Khalif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.23 10:02:59