问题
I have an AWS Ubuntu server that hosts a react front end running at 127.0.0.1:4100 and makes api calls to a Go app using port 127.0.0.1:1323. I installed Nginx and setup proxy pass for these two ports in /etc/nginx/sites-available/default
config file but I only get the front end getting called by Nginx. Using chrome inspect to check why the Go app is not serving some of the functionalities from the react app, I see this error
client.js:772 GET http://127.0.0.1:1323/api/ net::ERR_CONNECTION_REFUSED ERROR Error: Request has been terminated Possible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.
What am I doing wrong? Below is my default config file
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
location / {
proxy_pass http://127.0.0.1:4100;
}
location /api {
proxy_pass http://127.0.0.1:1323/;
}
}
回答1:
Your server is listening to port 80:
listen 80 default_server;
listen [::]:80 default_server;
So, you should make your request to that port:
GET http://127.0.0.1/api/ => http://127.0.0.1:1323/
GET http://127.0.0.1:80/api/ => http://127.0.0.1:1323/
GET http://127.0.0.1/ => http://127.0.0.1:4100/
GET http://127.0.0.1:80/ => http://127.0.0.1:4100/
Then nginx should correctly proxy your requests.
Update
To be more clear about nginx config.
server {
listen 80 default_server; // The port nginx is listening to ipv4
listen [::]:80 default_server; // The port nginx is listening to ipv6
server_name _;
location / { // When you call this location...
proxy_pass http://127.0.0.1:4100; // You'll be redirected to this location
}
location /api { // When you call this location...
proxy_pass http://127.0.0.1:1323/; // You'll be redirected to this location
}
}
Your configuration is okay according to nginx docs.
You said your client is trying to reach http://127.0.0.1:1323/api/
but It should be requesting http://127.0.0.1/api/
(whitour the port) to be redirected to http://127.0.0.1:1323/
.
Here's another example:
server {
listen 80;
server_name localhost anywebsite.com;
location ~* ^/MyApp {
proxy_pass http://localhost:5130;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_send_timeout 2m;
proxy_read_timeout 2m;
}
}
In this case, everytime my url ends with /MyApp
ex.: http://anywebsite.com/api/MyApp
I'm being proxyed to http://localhost:5130
. But if I try to access http://localhost:5130
or http://anywebsite.com:5130/api/MyApp
I won't be able because nginx is listening to port 80 only. If you want to access another port you need to specify like this:
server {
listen 80;
listen 5130;
[...]
来源:https://stackoverflow.com/questions/55504509/nginx-not-routing-calls-from-react-app-to-backend-app