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

部署React应用至Vercel后出现NOT FOUND错误,疑为__dirname解析问题

React应用部署Vercel后出现「NOT FOUND」问题排查与解决

问题描述

将React应用部署到Vercel平台后,访问链接时出现「NOT FOUND」提示,怀疑是代码中__dirname解析不正确导致的问题,附上服务端index.js代码:

// express acts as a server
import express from "express";
import dotenv from "dotenv";
import Connection from "./database/db.js";
import DefaultData from "./default.js";
import router from "./routes/route.js";
import cors from "cors";
import bodyParser from "body-parser";
import { v4 as uuid} from "uuid";
import * as path from "path";
import { fileURLToPath } from "url";

const app = express();

dotenv.config();
app.use(cors());
app.use(bodyParser.json({ extended: true }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use("/", router);
const PORT = process.env.PORT || 8000;

Connection();

const __dirname = path.dirname(fileURLToPath(import.meta.url));

console.log(__dirname);

if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, 'client', 'build')))

  app.get('/*', function (req, res) {
    res.sendFile(path.join(__dirname, 'client', 'build', 'index.html'))
  });
}

app.listen(PORT, () =>
  console.log(`Server is running successfully on Port ${PORT}`)
);

// DefaultData();

解决方案

  • 验证路径与构建产物
    通过Vercel日志查看__dirname的实际输出值,确认client/build目录是否存在于部署包内。同时确保Vercel部署流程中执行了React的构建命令(如npm run build),生成了正确的静态产物。

  • 修正路径解析逻辑
    替换依赖__dirname的路径拼接方式,改用动态路径解析避免环境差异:

    // 替换原生产环境代码块
    const buildPath = path.resolve('./client/build');
    app.use(express.static(buildPath));
    
    app.get('/*', (req, res) => {
      res.sendFile(path.join(buildPath, 'index.html'));
    });
    
  • 添加Vercel路由重写配置
    在项目根目录创建vercel.json文件,配置重写规则适配React单页应用路由:

    {
      "rewrites": [
        { "source": "/(.*)", "destination": "/index.html" }
      ]
    }
    

    该配置会将所有请求导向index.html,解决单页应用路由跳转时的404问题。

  • 确认环境变量生效
    Vercel生产环境会自动设置NODE_ENV=production,若存在变量未生效情况,可直接移除环境判断逻辑,强制启用静态文件服务与路由重写(仅用于生产部署场景)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:22:40