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

don*_*tke 2 nginx nginx-location nginx-reverse-proxy nginx-config

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

client.js:772 GET http://127.0.0.1:1323/api/ net::ERR_CONNECTION_REFUSED ERROR 错误:请求已终止 可能原因:网络离线、Access-Control-Allow-Origin 不允许 Origin、页面正在卸载等。

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

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

 } 
}
Run Code Online (Sandbox Code Playgroud)

tga*_*cia 7

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

listen 80 default_server; 
listen [::]:80 default_server; 
Run Code Online (Sandbox Code Playgroud)

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

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/
Run Code Online (Sandbox Code Playgroud)

那么 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

 } 
}
Run Code Online (Sandbox Code Playgroud)

根据 nginx 文档,您的配置没问题。

您说您的客户端正在尝试访问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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

server {
    listen 80; 
    listen 5130; 

[...]
Run Code Online (Sandbox Code Playgroud)