问题描述
我有一个 react 前端和 node 后端,由于某种原因它不会向后端发出正确的请求。
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/;
}
解决方法
我注意到它提出了错误的请求,因为 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
}
解释
要将请求传递给 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