部署create-react-app到Heroku后无法连接自定义server.js的问题
Hey there! Let's break down why your Create React App isn't connecting to your custom server.js on Heroku, even after setting up the proxy. Here are the most actionable checks and fixes to get things working:
1. Fix your package.json proxy configuration
Forget specifying a port in the proxy for Heroku! Since your frontend and backend run on the same Heroku dyno (and same auto-assigned port), you only need to point the proxy to your API path prefix (or root if your API is at the root).
- ❌ Wrong (local dev-only):
"proxy": "http://localhost:5000" - ✅ Correct:
"proxy": "/api"(or just"/"if your API routes start at the root)
2. Make sure server.js serves React's static build files
After Heroku runs npm run build, your server needs to serve the compiled React files. Add this to your server.js (adjust the path if your React app is in a subfolder like client):
const path = require('path'); // Serve static files from the React build folder app.use(express.static(path.join(__dirname, 'build'))); // Catch all React routing requests and return the app's index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'build', 'index.html')); });
3. Verify your package.json scripts are set up for Heroku
Heroku uses the start script to launch your app—this needs to point to your server.js, not React's dev server. Example:
"scripts": { "start": "node server.js", "build": "react-scripts build", "dev": "concurrently \"node server.js\" \"react-scripts start\"" // For local dev only }
4. Check Heroku logs for explicit errors
This is non-negotiable—run heroku logs --tail in your terminal to see real-time error messages. Common issues you might spot:
- Hardcoded port numbers: Replace
5000withprocess.env.PORT || 5000in your server listen code:const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(`Server up on port ${PORT}`)); - Missing dependencies: Ensure packages like
expressare in yourdependencies(not justdevDependencies—Heroku skips dev dependencies by default).
5. Use relative paths for API requests
With the proxy set up, your frontend should use relative paths for API calls, not full URLs. For example:
- ❌ Wrong:
fetch('http://localhost:5000/api/users') - ✅ Correct:
fetch('/api/users')
This works both locally (proxy forwards to your dev server) and on Heroku (requests go to the same dyno's API routes).
内容的提问来源于stack exchange,提问作者HaulinOats

