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

Vercel部署Express.js应用时public目录静态文件404问题

解决Express.js部署Vercel后静态文件404问题

问题根源

本地运行正常但Vercel部署后静态文件404,核心原因有两个:

  • Vercel路由配置将所有请求直接导向server.js,未优先处理静态文件
  • express.static使用相对路径,部署后Node进程的工作目录变化导致路径匹配错误

解决方案

1. 修正vercel.json路由配置

让静态文件请求优先被Vercel静态服务处理,剩余请求再交给Node服务器:

{
  "version": 2,
  "builds": [
    {
      "src": "server.js",
      "use": "@vercel/node"
    },
    {
      "src": "public/**/*",
      "use": "@vercel/static"
    }
  ],
  "routes": [
    // 优先匹配静态文件后缀的请求,直接指向public目录
    {
      "src": "/(.*\\.(html|css|js|png|jpg|svg)$)",
      "dest": "/public/$1"
    },
    // 其他请求交给server.js处理
    {
      "src": "/(.*)",
      "dest": "/server.js"
    }
  ]
}

2. 改用绝对路径配置静态文件服务

在server.js中使用__dirname拼接绝对路径,避免部署后路径错误:

const express = require('express');
const path = require('path');
const app = express();

// 用绝对路径指向public目录
app.use(express.static(path.join(__dirname, 'public')));

// ... 其他业务路由

const port = process.env.PORT || 3000;
app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

3. 添加路径fallback路由

确保访问根路径/或/admin时能正确返回对应HTML文件:

const fs = require('fs');

// 根路径返回index.html
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// /admin路径返回admin.html
app.get('/admin', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});

// 可选:处理所有未匹配路径,尝试返回对应HTML,不存在则返回index.html(适用于SPA场景)
app.get('*', (req, res) => {
  const targetPath = path.join(__dirname, 'public', req.path.endsWith('.html') ? req.path : `${req.path}.html`);
  fs.access(targetPath, fs.constants.F_OK, (err) => {
    if (err) {
      res.sendFile(path.join(__dirname, 'public', 'index.html'));
    } else {
      res.sendFile(targetPath);
    }
  });
});

验证步骤

  1. 推送修改后的代码到Vercel关联仓库
  2. 等待部署完成后,访问/、/admin.html或/admin测试页面加载情况
  3. 查看Vercel日志,确认404错误已消除

内容的提问来源于stack exchange,提问作者kris

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 07:03:41