如何在Heroku上同时部署ReactJS前端与NodeJS(Express)后端
Hey there! Let's get your React + Node.js app fully deployed on Heroku—you're almost there. Here's how to fix the backend deployment and proxy confusion step by step:
First, organize your code so both frontend and backend live in the same repository. Move your React project into a subfolder (like client/) within your Node.js backend project. This lets Heroku deploy both parts from one app instance.
Update your Express server code to host the React build files in production. This way, when users visit your Heroku URL, the backend serves your frontend, and API requests stay on the same domain:
const path = require('path'); const express = require('express'); const app = express(); // Your existing API routes go here (make sure they start with /api to avoid conflicts) app.get('/api/your-endpoint', (req, res) => { // Handle API logic }); // Serve React static files in production if (process.env.NODE_ENV === 'production') { // Point to the built React files app.use(express.static(path.join(__dirname, 'client/build'))); // Catch all non-API routes and return React's index.html (for SPA routing) app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'client/build', 'index.html')); }); } // Use Heroku's dynamic port, fall back to 3004 for local dev const PORT = process.env.PORT || 3004; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
In your root directory's package.json, add a heroku-postbuild script. Heroku runs this automatically after installing backend dependencies to build your React app:
{ "scripts": { "start": "node server.js", // Your backend start command "heroku-postbuild": "cd client && npm install && npm run build" }, "engines": { "node": "16.x", // Match your local Node version "npm": "8.x" } }
- Local Development: Keep the
"proxy": "http://localhost:3004"line in your React project'spackage.json—this lets local requests proxy to your backend. - Production: Update all your API calls to use relative paths instead of
http://localhost:3004. For example, changehttp://localhost:3004/api/itemsto/api/items. Since frontend and backend share the same domain on Heroku, these requests will automatically hit your backend.
Also, add "homepage": "." to your React project's package.json to ensure build assets use relative paths:
{ "homepage": "." }
Commit all your changes to Git, then push to Heroku:
git add . git commit -m "Set up combined frontend/backend deployment" git push heroku main
Once deployed, your Heroku app will serve both the React frontend and Node.js backend. Visiting your URL will load the frontend, and all API requests will work without extra proxy setup.
内容的提问来源于stack exchange,提问作者Mich

