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

求助:将React+Node应用部署至DigitalOcean/Heroku时前端无法显示

Hey there, let's troubleshoot why your React frontend isn't loading on Heroku. Since your app works perfectly locally, the issue almost certainly lies in how Heroku handles the build process and static file serving. Here's a step-by-step breakdown of fixes to get your app running:

1. Fix Your Root package.json Scripts & Config

Heroku needs clear instructions to build your React app and start your Node server. If your project has a separate client folder for React, update your root package.json with these scripts:

"scripts": {
  "start": "node server.js", // Replace with your actual Node entry file
  "build": "cd client && npm install && npm run build"
},
"engines": {
  "node": ">=16.x", // Match your local Node version
  "npm": ">=8.x"
}

The engines field ensures Heroku uses a compatible Node/NPM version, avoiding build failures from version mismatches.

2. Configure Your Node Server to Serve Static React Files

Your backend needs to serve the compiled React build folder in production. Add this code to your server file (e.g., server.js), after all your API routes:

const path = require('path');

// Serve static files from React's build directory
app.use(express.static(path.join(__dirname, 'client/build')));

// Catch-all route: send React's index.html for any non-API requests
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'client/build/index.html'));
});

This ensures any frontend route is handled by React's router, and static assets (CSS, JS) load correctly.

3. Update React's package.json for Correct Asset Paths

In your client/package.json, add a homepage field to fix relative path issues in the build:

"homepage": "."

This prevents 404 errors for static assets when the app is hosted on Heroku.

4. Check Heroku Build Logs for Hidden Errors

Run this command in your terminal to view real-time logs:

heroku logs --tail

Or check logs via your Heroku dashboard (More > View Logs). Common issues to look for:

  • Missing dependencies in client/package.json (make sure the client folder isn't ignored in .gitignore)
  • Hardcoded port number: Ensure your server uses process.env.PORT || 5000 instead of a fixed port (Heroku assigns dynamic ports)
  • Buildpack issues: If Heroku doesn't detect the Node buildpack automatically, add it manually with heroku buildpacks:add heroku/nodejs

5. Re-Deploy After Making Changes

Commit your fixes and push to Heroku:

git add .
git commit -m "Fix Heroku deployment config"
git push heroku main

Once deployed, run heroku open to test your app.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:23:16