NGINX 没有将调用从 React 应用程序路由到后端应用程序

NGINX not routing calls from react app to backend app

我有一个 AWS Ubuntu 服务器,它在 127.0.0.1:4100 托管一个反应前端 运行 并使用端口 127.0.0.1 对 Go 应用程序进行 api 调用: 1323.我在 /etc/nginx/sites-available/default 配置文件中为这两个端口安装了 Nginx 和设置代理通行证,但我只得到 Nginx 调用的前端。使用 chrome inspect 来检查为什么 Go 应用程序没有提供 React 应用程序的某些功能,我看到了这个错误

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.

我做错了什么?下面是我的默认配置文件

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/; 

 } 
}

您的服务器正在侦听端口 80:

listen 80 default_server; 
listen [::]:80 default_server; 

因此,您应该向该端口发出请求:

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/

然后 nginx 应该正确地代理您的请求。

更新

更清楚nginx的配置。

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

 } 
}

你的配置没问题according to nginx docs.

您说您的客户端正在尝试访问 http://127.0.0.1:1323/api/,但它应该请求 http://127.0.0.1/api/(没有端口)重定向到 http://127.0.0.1:1323/

这是另一个例子:

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;
    }
}

在这种情况下,每次我的 url 都以 /MyApp 结尾,例如:http://anywebsite.com/api/MyApp 我被代理到 http://localhost:5130。但是,如果我尝试访问 http://localhost:5130http://anywebsite.com:5130/api/MyApp 我将无法访问,因为 nginx 仅侦听端口 80。如果你想访问另一个端口,你需要这样指定:

server {
    listen 80; 
    listen 5130; 

[...]