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

kgc*_*usi 1 nginx amazon-web-services node.js nginx-reverse-proxy

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

nginx给出的错误日志

111: Connection refused) while connecting to upstream, server: _, request: "GET /api/info HTTP/1.1", upstream: "http://127.0.0.1:5000/info"
Run Code Online (Sandbox Code Playgroud)

我注意到它提出了错误的请求,因为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/;
        }
Run Code Online (Sandbox Code Playgroud)

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

Đăn*_*inh 5

我注意到它提出了错误的请求,因为 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
}
Run Code Online (Sandbox Code Playgroud)

解释

来自nginx 文档

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

location /some/path/ {
    proxy_pass http://www.example.com/link/; 
}
Run Code Online (Sandbox Code Playgroud)

请注意,在上面的第一个示例中,代理服务器的地址后面跟着一个 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