Nginx 代理将 Nodejs 传递给 React 应用程序 行动解释

问题描述

我有一个 react 前端和 node 后端,由于某种原因它不会向后端发出正确的请求。

Nginx给出的错误日志

111: Connection refused) while connecting to upstream,server: _,request: "GET /api/info HTTP/1.1",upstream: "http://127.0.0.1:5000/info"

我注意到它发出了错误的请求,因为 http://127.0.0.1:5000/info 应该是 http://127.0.0.1:5000/api/info

我的认配置

server {
        listen 80 default_server;
        listen [::]:80 default_server;

        root /var/www/{{AppName}}/frontend/build;

        server_name {{myDomainName}};

        location / {
                try_files $uri $uri/ =404;
        }

        location /api/ {
                proxy_pass http://localhost:5000/;
        }

当我访问我的网站时,它只会显示错误 404

解决方法

我注意到它提出了错误的请求,因为 http://127.0.0.1:5000/info 应该是 http://127.0.0.1:5000/api/info

行动

去掉代理地址末尾的'/'

location /api/ {
    proxy_pass http://localhost:5000; # remove the '/' at the end
}

解释

来自nginx documentation

要将请求传递给 HTTP 代理服务器,proxy_pass 指令 在一个位置内指定。例如:

location /some/path/ {
    proxy_pass http://www.example.com/link/; 
}

请注意,在上面的第一个示例中,代理服务器的地址后跟一个 URI,/link/。 如果 URI 与地址一起指定,它将替换部分 与位置参数匹配的请求 URI。例如, 这里带有 /some/path/page.html URI 的请求将被代理到 http://www.example.com/link/page.html

在您的情况下,URI 是 /,它替换了请求 URI 中的 /api/。所以: http://yourserver/api/info 将被代理到 http://127.0.0.1:5000/info