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

标签 nginx nginx-location nginx-reverse-proxy nginx-config

我有一个 AWS Ubuntu 服务器,它托管在 127.0.0.1:4100 运行的 React 前端,并使用端口 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 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; 

[...]

关于NGINX 没有将调用从 React 应用程序路由到后端应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55504509/

相关文章:

docker - Nginx 405当另一个站点重定向到我的vue应用程序时不允许

nginx - 使用 nginx map 指令动态设置代理上游

docker - 当上游节点不可用时,Nginx 容器退出并显示代码 1

redirect - 如何使用 Nginx 重定向到不同的域?

c - nginx 基于前缀的位置处理实现的效率如何?

Nginx 403 禁止位置和本地主机

javascript - 使用 Nginx 在端口上绑定(bind) Node.js 应用程序

ruby-on-rails - 如何让 systemd 使用 Puma 重启 Rails App

http - php-fpm 每天停止多次

sockets - 我怎样才能让 uWSGI 监听另一台机器?