Express与create-react-app API请求咨询:已配置本地代理
Hey there! Let's walk through how to make the most of your proxy configuration and smooth out API requests between your React app (running on localhost:3000) and Express backend (localhost:3001). First, let's confirm your setup is good to go, then dive into examples, troubleshooting, and production tips.
1. Verify Your Proxy Configuration
Your package.json proxy setup ("proxy": "http://localhost:3001") is exactly what create-react-app's dev server needs to forward requests to your backend. A quick heads-up: this only works in development mode (when you run npm start). For production, we'll cover a different approach later.
Just make sure:
- Your Express backend is actively running on
localhost:3001 - You've restarted your React dev server after adding the proxy line (changes to
package.jsonrequire a restart to take effect)
2. Making API Requests (Using Axios)
Since you already have Axios installed, here's how to send requests without needing to type the full backend URL every time—thanks to the proxy:
Example 1: GET Request
import axios from 'axios'; const fetchUsers = async () => { try { // Notice we use the relative path /api/users instead of http://localhost:3001/api/users const response = await axios.get('/api/users'); console.log('Fetched users:', response.data); // Use the data in your component state here } catch (err) { console.error('Failed to fetch users:', err.message); } };
Example 2: POST Request
const createUser = async (newUser) => { try { const response = await axios.post('/api/users', newUser); console.log('Created user:', response.data); } catch (err) { console.error('Failed to create user:', err.response?.data || err.message); } };
Behind the scenes, the React dev server automatically forwards these requests to http://localhost:3001/api/users—no CORS issues to worry about in development!
3. Common Troubleshooting Tips
If you run into issues, here's what to check first:
404 Errors on Requests
- Double-check your Express route definitions. Make sure the path matches exactly (e.g., if your React app calls
/api/users, your Express code should haveapp.get('/api/users', ...)).
Example Express route setup:const express = require('express'); const app = express(); // Don't forget to parse JSON request bodies! app.use(express.json()); app.get('/api/users', (req, res) => { res.json([{ id: 1, name: 'Patrick' }, { id: 2, name: 'Jane' }]); }); app.listen(3001, () => console.log('Backend running on port 3001')); - Confirm your backend is actually running on port 3001 (no other apps using that port!).
Request Body is undefined in Express
- You need to tell Express to parse JSON request bodies. Add
app.use(express.json())at the top of your Express server file (before defining routes). For older Express versions, you might needbody-parserinstead, butexpress.json()works for v4.16+.
CORS Errors (Unexpected in Development)
- If you're still seeing CORS errors, it's likely the proxy isn't active. Restart your React dev server—remember, changes to
package.jsondon't take effect until you stop and restartnpm start.
4. Production Setup
When you build your React app with npm run build, you'll get a static build folder. Instead of using the proxy, you can host these static files directly from your Express server to avoid cross-origin issues:
const path = require('path'); const express = require('express'); const app = express(); // Parse JSON bodies app.use(express.json()); // Define your API routes FIRST app.get('/api/users', (req, res) => { res.json([{ id: 1, name: 'Patrick' }, { id: 2, name: 'Jane' }]); }); // Serve static files from the React build folder app.use(express.static(path.join(__dirname, 'build'))); // Catch-all route: send all non-API requests to React's index.html app.get('*', (req, res) => { res.sendFile(path.join(__dirname, 'build', 'index.html')); }); // Run the server on your preferred port (e.g., 3000) app.listen(3000, () => console.log('Production server running on port 3000'));
Now both your frontend and backend run on the same server, so no proxy or CORS configuration is needed!
内容的提问来源于stack exchange,提问作者patrickhuang94

