【问题标题】:Nginx Proxy Pass Nodejs to React ApplicationNginx 代理将 Nodejs 传递给 React 应用程序
【发布时间】:2021-09-09 08:52:00
【问题描述】:

我有一个 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

【问题讨论】:

    标签: node.js amazon-web-services nginx nginx-reverse-proxy


    【解决方案1】:

    我注意到它发出了错误的请求,因为 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

    【讨论】:

    • 我已经解决了这个问题,但你是第一个发布答案的,哈哈!谢谢!
    猜你喜欢
    • 2019-01-27
    • 2014-04-06
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 1970-01-01
    相关资源
    最近更新 更多