简体   繁体   English

Nginx 代理将 Nodejs 传递给 React 应用程序

[英]Nginx Proxy Pass Nodejs to React Application

I have a front end of react and backend of node, for some reason it wont make the right request to the backend.我有一个反应前端和节点后端,由于某种原因它不会向后端发出正确的请求。

The error log given by nginx nginx给出的错误日志

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

I noticed that it makes the wrong request because the http://127.0.0.1:5000/info should be http://127.0.0.1:5000/api/info我注意到它提出了错误的请求,因为http://127.0.0.1:5000/info应该是http://127.0.0.1:5000/api/info

My default config我的默认配置

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

When I visit my website it just errors me out with Error 404当我访问我的网站时,它只会显示错误 404

I noticed that it makes the wrong request because the http://127.0.0.1:5000/info should be http://127.0.0.1:5000/api/info我注意到它提出了错误的请求,因为http://127.0.0.1:5000/info应该是http://127.0.0.1:5000/api/info

Action行动

Remove the '/' at the end of the proxy address去掉代理地址末尾的'/'

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

Explain解释

From nginx documentation来自nginx 文档

To pass a request to an HTTP proxied server, the proxy_pass directive is specified inside a location.为了将请求传递到 HTTP 代理服务器,proxy_pass 指令在一个位置内指定。 For example:例如:

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

Note that in the first example above, the address of the proxied server is followed by a URI, /link/.请注意,在上面的第一个示例中,代理服务器的地址后跟一个 URI,/link/。 If the URI is specified along with the address, it replaces the part of the request URI that matches the location parameter .如果 URI 与地址一起指定,它将替换请求 URI 中与位置参数匹配的部分 For example, here the request with the /some/path/page.html URI will be proxied to http://www.example.com/link/page.html例如,这里带有 /some/path/page.html URI 的请求将被代理到http://www.example.com/link/page.html

In your case, the URI is / , it replaces /api/ in the request URI.在您的情况下,URI 是/ ,它替换请求 URI 中的/api/ So: http://yourserver/api/info will be proxied to http://127.0.0.1:5000/info所以: http://yourserver/api/info将被代理到http://127.0.0.1:5000/info

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM