[英]Nginx with Frontend and Backend Server
我正在開發一個 CTF,它將被下載並在 VM 上本地運行。 CTF 的 IP 地址因用戶而異。 我有一個在端口 3000 上運行的前端服務器(React.js)。我正在向后端服務器發出這樣的請求:
fetch("http://localhost:5000/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
})
后端服務器(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;
}
當 CTF 啟動時,用戶將獲得一個私有 IP,如下所示:192.168.2.136。 我的問題是,我如何向后端發出請求,因為fetch("http://localhost:5000/login)
不會從后端獲取。我需要做fetch("http://192.168.2.136:5000/login
讓它工作。這個問題可以用 nginx 解決,還是我需要尋找一種方法來在 VM 啟動時獲取私有 IP 地址?
對於任何有同樣問題的人,我通過在 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.