[英]Nginx with Frontend and Backend Server
I'm working on a CTF that will be downloaded and run locally on a VM.我正在开发一个 CTF,它将被下载并在 VM 上本地运行。 The IP address of the CTF will be different for each user.
CTF 的 IP 地址因用户而异。 I have a frontend server (React.js) running on port 3000. I'm making a request like so to the backend server:
我有一个在端口 3000 上运行的前端服务器(React.js)。我正在向后端服务器发出这样的请求:
fetch("http://localhost:5000/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
The backend server (express.js) is running on port 5000. I have nginx configured to route port 3000 request to port 80.后端服务器(express.js)在端口 5000 上运行。我将 nginx 配置为将端口 3000 请求路由到端口 80。
listen 80 default_server;
listen [::]:80 default_server;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
When the CTF is booted a user will get a private IP like so: 192.168.2.136.当 CTF 启动时,用户将获得一个私有 IP,如下所示:192.168.2.136。 My question is, how do I make request to the backend because
fetch("http://localhost:5000/login)
will not fetch from the backend. I will need to do fetch("http://192.168.2.136:5000/login
for it to work. Can this issue be resolved with nginx, or will I need to look into a way to get the private IP address when the VM boots?我的问题是,我如何向后端发出请求,因为
fetch("http://localhost:5000/login)
不会从后端获取。我需要做fetch("http://192.168.2.136:5000/login
让它工作。这个问题可以用 nginx 解决,还是我需要寻找一种方法来在 VM 启动时获取私有 IP 地址?
For anyone with the same issue, I fixed it by using a server name in nginx and properly routing the backend traffic to my backend server like so:对于任何有同样问题的人,我通过在 nginx 中使用服务器名称来修复它,并将后端流量正确路由到我的后端服务器,如下所示:
server {
listen 80;
server_name resume.tm;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
}
location /api/ {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.