React+Express联调遇ECONNREFUSED错误,代理请求失败求助
Hey there, let's work through this proxy error you're facing—this is a super common hiccup when setting up React + Express locally, so we'll get it sorted out.
First, let's break down the issue: the ECONNREFUSED error means your React dev server (running on port 3000) can't establish a connection to your Express backend on port 3001. Here are the most likely fixes, ordered by how often they solve the problem:
1. Double-check your Express server is actually running on port 3001
This is the #1 culprit. Before anything else:
- Make sure you've started your Express server (run
node server.jsor whatever your entry file is—don't forget to install dependencies first withnpm installif you haven't). - Verify the server is listening on port 3001. Check your Express code for the listen call: it should look like
app.listen(3001, () => console.log('Server running on port 3001')). - Test the backend directly: open your browser or use
curl http://localhost:3001/users—if you don't get a response, fix your backend first (check for syntax errors, missing routes, etc.) before worrying about the proxy.
2. Fix your React proxy configuration
It looks like there's a typo in your proxy URL from the error message (http://localhost/3001 instead of http://localhost:3001). That's a common mistake!
- Open your React project's
package.jsonfile. - Find the
"proxy"field (add it if it's missing) and set it to:"proxy": "http://localhost:3001" - Important: Restart your React development server after changing this—changes to
package.jsondon't take effect until you restartnpm start.
3. Check for port conflicts
Port 3001 might be occupied by another program. To check:
- On Mac/Linux, run
lsof -i :3001in your terminal. If any processes show up, kill them withkill -9 <PID>(replace<PID>with the process ID from the output). - On Windows, open Command Prompt and run
netstat -ano | findstr :3001. Find the PID, then open Task Manager, go to the Details tab, and end that process. - Alternatively, change your Express server to use a different port (like 3002) and update your React proxy config to match.
4. Ensure your Express server is listening on the right interface
In rare cases, your Express server might be bound to a specific IP instead of allowing connections from localhost. Make sure your listen call doesn't restrict to a specific IP unless you need to:
- Instead of
app.listen(3001, '192.168.1.100', ...), use the default (which listens on all interfaces) or explicitly specifylocalhost:app.listen(3001, 'localhost', () => { console.log('Server running on http://localhost:3001'); });
Once you've worked through these steps, your proxy should start working like it did in the example project. Remember to test incrementally—get the backend running first, then verify the proxy config, and you'll be good to go.
内容的提问来源于stack exchange,提问作者Brandon Benefield

