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

本地正常但Vercel部署提示找不到public/index.html问题求助

Vercel部署后无法读取public/index.html的问题排查

问题描述

本地环境中public/index.html可正常渲染,以下读取文件的代码运行正常:

async function readFileContent(filePath) {
    try {
        const response = await fs.readFile("public/index.html", "utf-8");
        return response;
    } catch (error) {
        console.log(`Error reading file ${filePath}:`, error);
        return "Error rendering file";
    }
}

但部署至Vercel后,出现文件不存在的报错:

Error reading file public/index.html: [Error: ENOENT: no such file or directory, open 'public/index.html'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'public/index.html'
}

确认public/index.html文件存在,当前vercel.json配置如下:

{
    "version": 2,
    "builds": [{ "src": "server.js", "use": "@vercel/node" }],
    "rewrites": [{ "source": "/(.*)", "destination": "/index.html" }],
    "routes": [{ "src": "/", "dest": "server.js" }]
}

问题原因

  • 相对路径失效:本地运行时Node.js工作目录为项目根目录,但Vercel部署后,Node函数的工作目录会变为函数代码所在的子路径,直接使用相对路径public/index.html无法定位到文件。
  • 静态目录未被打包:Vercel默认只打包builds配置指定的文件(此处为server.js)及依赖,public目录未被包含到函数的部署包中,导致运行时无法访问。
  • 路由配置冲突:vercel.json中同时配置了rewrites和routes,rewrites将所有请求指向index.html,与routes中根路径指向server.js的规则冲突,干扰了文件访问逻辑。

解决方案

1. 使用绝对路径定位文件

通过path模块结合__dirname拼接绝对路径,确保无论工作目录如何变化都能找到文件:

const path = require('path');
const fs = require('fs').promises;

async function readFileContent(filePath) {
    try {
        const fullPath = path.join(__dirname, 'public', 'index.html');
        const response = await fs.readFile(fullPath, "utf-8");
        return response;
    } catch (error) {
        console.log(`Error reading file ${filePath}:`, error);
        return "Error rendering file";
    }
}

2. 调整Vercel构建配置

修改vercel.json,将public目录包含到函数部署包中,并移除冲突的rewrites规则:

{
    "version": 2,
    "builds": [{ 
        "src": "server.js", 
        "use": "@vercel/node",
        "include": ["public/**/*"]
    }],
    "routes": [{ "src": "/", "dest": "server.js" }]
}

3. 检查部署日志

查看Vercel构建过程的日志,确认public目录是否被正确复制到部署输出目录。若未复制,需调整项目结构或添加构建脚本确保静态目录被同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 23:01:29