NGINX没有将响应应用程序的呼叫路由到后端应用程序

问题描述 投票:1回答:1

我有一个AWS Ubuntu服务器,它托管一个运行在127.0.0.1:4100的反应前端,并使用端口127.0.0.1:1323对Go应用程序进行api调用。我在/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错误:请求已终止可能的原因:网络脱机,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/; 

 } 
}
nginx nginx-location nginx-reverse-proxy nginx-config
1个回答
0
投票

您的服务器正在侦听端口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;
    }
}

在这种情况下,每次我的网址结束时/MyApp结束:http://anywebsite.com/api/MyApp我被代理到http://localhost:5130。但是,如果我尝试访问http://localhost:5130http://anywebsite.com:5130/api/MyApp,我将无法访问,因为nginx只能侦听端口80。如果要访问另一个端口,则需要指定如下:

server {
    listen 80; 
    listen 5130; 

[...]
© www.soinside.com 2019 - 2024. All rights reserved.