React应用调用托管VM本地Node服务器的请求路径异常问题
Hey there, let's break down what's happening here and fix it step by step!
Why this is happening
Your React app runs in the user's browser, not directly on your VM. When you use a relative path like /api/... in axios, the browser automatically appends it to the current page's domain (your VM's IP address) — not the localhost:8080 you're thinking of. To the browser, localhost refers to the machine running the browser, not your VM's internal server. That's why Postman works (you're directly targeting the VM's 8080 port) but the browser doesn't.
Solution 1: Nginx Reverse Proxy (Recommended for Production)
This is the most robust approach — we'll make Nginx forward all /api requests to your VM's 8080 server.
- Open your Nginx config file (usually located at
/etc/nginx/sites-available/defaultor in/etc/nginx/conf.d/). - Add a
location /apiblock alongside your existing React static file setup:
server { listen 80; server_name your-vm-ip-address; # Leave blank to listen for all requests # Serve React static files location / { root /path/to/your/react/build/folder; try_files $uri $uri/ /index.html; # Critical for React single-page routing } # Forward API requests to your 8080 server location /api { proxy_pass http://localhost:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
- Validate the config to avoid errors:
sudo nginx -t
- Restart Nginx to apply changes:
sudo systemctl restart nginx
Now, when the browser sends a request like http://your-vm-ip/api/..., Nginx will silently forward it to http://localhost:8080/api/... on your VM — no changes needed to your React code.
Solution 2: React Environment Variables (Quick Fix)
If you don't want to tweak Nginx, you can hardcode your VM's API endpoint into React's build config.
- Create a
.env.productionfile in your React project root:
REACT_APP_API_BASE_URL=http://your-vm-ip-address:8080
Note: React only recognizes environment variables prefixed with REACT_APP_.
- Update your axios setup to use this variable:
import axios from 'axios'; const apiClient = axios.create({ baseURL: process.env.REACT_APP_API_BASE_URL, }); // Use this client for all API calls apiClient.get('/api/your-endpoint') .then(res => console.log(res.data)) .catch(err => console.error(err));
- Rebuild your React app and redeploy the
buildfolder to Nginx:
npm run build
The downside here is you'll need to rebuild and redeploy if your VM's IP changes.
Solution 3: Development Proxy (For Local Testing)
If you run into this issue while developing locally (not on the VM), add this line to your React project's package.json:
"proxy": "http://your-vm-ip-address:8080"
This only works with npm start (create-react-app's dev server) — it won't help with your production build on Nginx.
内容的提问来源于stack exchange,提问作者Bogdan Daniel

