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

前端置于后端文件夹的MERN应用部署Heroku后报404如何解决

问题定位

核心错误由两个原因导致:

  1. 前端生产包未实际生成:查看Heroku构建日志,heroku-postbuild阶段执行cd mappinapp && npm install && npm run build后,只有npm install的审计输出,没有build命令的执行记录,说明前端项目的package.json缺失正确的build脚本,或脚本执行异常被静默跳过,最终没有生成build文件夹。
  2. 后端静态资源配置错误:你注释了express静态资源服务代码,且路径拼接规则有误,就算build文件夹生成也无法正确加载资源。

修复步骤

1. 配置前端构建脚本

打开前端根目录mappinapp下的package.json,确认scripts字段存在正确的build配置:

{
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }
}

如果缺失react-scripts依赖,本地执行cd mappinapp && npm install react-scripts --save后再提交代码。

2. 修正后端index.js配置

恢复静态资源服务代码,调整路径逻辑,同时保留通配路由适配SPA前端路由:

// api路由放在前面
app.use("/api/users", userRoute);
app.use("/api/pins", pinRoute);

// 开启静态资源服务,__dirname对应api文件夹根目录,不需要额外加/api前缀
app.use(express.static(path.join(__dirname, "mappinapp/build")));

// 所有非api请求返回前端入口文件,处理刷新404问题
app.get("*", (req, res) => {
  res.sendFile(path.join(__dirname, "mappinapp", "build", "index.html"));
});

你之前路径开头加的/会导致path.join从系统根目录开始寻址,而非基于当前api文件夹的相对路径,是路径报错的直接原因。

3. 修复CSP报错

你配置的CSP规则过于严格,限制了内联资源和favicon加载,修改mappinapp/public/index.html中的CSP元标签:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;" />

4. 重新部署

提交所有修改后执行git push heroku main重新构建部署,即可正常访问站点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:39:03