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

如何将MERN应用栈部署至Vercel/Netlify?部署404问题求助

MERN栈部署Vercel/Netlify出现404的解决方法

一、Vercel部署配置

1. 前端(client文件夹)配置

  • 确保前端package.json里有正确的build命令,比如React项目的"build": "react-scripts build",构建产物会生成在client/build目录。
  • 在Vercel项目设置中,Root Directory指定为client,让平台识别前端项目并完成构建。
  • 若前端用React Router等单页路由,在client/public下创建_vercel.json文件,配置路由 fallback:
{
  "rewrites": [
    { "source": "/(.*)", "destination": "/index.html" }
  ]
}

2. 后端(server文件夹)配置

  • Vercel通过Serverless Functions托管后端,可在项目根目录创建vercel.json配置函数入口:
{
  "functions": {
    "server/*.js": {
      "runtime": "@vercel/node@2.x"
    }
  },
  "routes": [
    { "src": "/api/(.*)", "dest": "/server/index.js" }
  ]
}
  • 后端不要硬编码端口,改用process.env.PORT获取平台分配的端口:
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server running on port ${port}`));

二、Netlify部署配置

1. 前端(client文件夹)配置

  • 确认client/package.json的build命令正确,Netlify默认执行npm run build,产物指向client/build。
  • 在Netlify项目设置的Build & Deploy中:
    • Base directory设为client
    • Build command设为npm run build
    • Publish directory设为build
  • 单页路由的404问题,在client/public创建_redirects文件,添加:
/* /index.html 200

2. 后端(server文件夹)配置

  • Netlify用Netlify Functions托管后端,在项目根目录创建netlify/functions文件夹,将后端逻辑拆分为单个函数文件,比如netlify/functions/api.js:
const express = require('express');
const serverless = require('serverless-http');

const app = express();
const router = express.Router();

// 你的API路由逻辑示例
router.get('/hello', (req, res) => {
  res.json({ message: 'Hello from Netlify Functions!' });
});

app.use('/.netlify/functions/api', router);

module.exports.handler = serverless(app);
  • 安装依赖:npm install serverless-http --save
  • 在netlify.toml中配置函数与前端产物路径:
[build]
  functions = "netlify/functions"
  publish = "client/build"

三、通用排查点

  • 检查前端API请求地址,部署后要调用平台托管的后端地址,不要用本地http://localhost:5000,建议用环境变量配置API_BASE_URL。
  • 确认.gitignore未忽略必要文件,比如client/build无需忽略,平台会自行构建。
  • 查看平台部署日志,日志会显示构建或启动过程中的错误(如依赖安装失败、端口冲突等),以此定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:46:19