[英]Nginx not working with Node.js + Socket.io
我一直在努力使Nginx / React應用程序連接到我的Node.js后端,該后端在我的開發環境中可以正常工作。 我的前端和后端部署在同一台VM上各自的Docker容器中。 Nginx容器可以直接與Node.js容器通信,並且可以確認它正常工作,因為其他get / post請求可以正常工作。
這是我最初的Nginx配置。
server {
listen 80;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
//This is the initial route to connect to socket.io
location /api/notices {
proxy_pass http://nodejs:8000;
}
location ~ ^/api/infoblock/[0-9a-zA-Z]+$ {
proxy_pass http://nodejs:8000;
}
}
這是我在控制台中遇到的錯誤:
POST http://domain_name/socket.io/?EIO=3&transport=polling&t=MVFZtgP 405 (Not Allowed)
我在網上做了更多研究,並被告知也要添加以下內容:
location /socket.io/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-NginX-Proxy true;
proxy_set_header Host $host;
proxy_pass http://nodejs:8000;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $http_host;
proxy_http_version 1.1;
proxy_cache_bypass $http_upgrade;
}
當我這樣做時,405錯誤消失了,但是似乎實際上什么都沒有發生。 我沒有從socket.io連接中獲取任何數據,並且在控制台中沒有拋出任何異常。
我不確定該怎么做。 我已經嘗試了很多在網上找到的“解決方案”,但似乎無法弄清為什么socket.io連接不起作用,但是正常的get / post請求可以解決。
這是我從前端進行連接的方式,再次證實了這在我的開發環境中可以正常工作。
let socket = socketIOClient("/api/notices");
socket.on("NoticesReact", this._socketNotices);
如何修復Nginx配置以與Node.js + Socket.io一起使用
經過數小時的嘗試來解決這個問題。 我知道了,但是我不確定為什么。
這不是最初發布的,但這是我的后端socket.io代碼如下所示:
io.of("/api/notices").on("connection", socket => {...})
在嘗試了幾乎所有內容之后,我決定刪除我的自定義名稱空間.of("/api/notices")
,這是將套接字限制為名稱空間的一種方式。 這在開發中起作用,並在socket.io上進行了記錄 。
所以現在我的Nginx配置看起來像這樣:
server {
listen 80;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /socket.io/ {
proxy_pass http://nodejs:8000;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location ~ ^/api/infoblock/[0-9a-zA-Z]+$ {
proxy_pass http://nodejs:8000;
}
}
神奇地……一切正常? 但是我不知道為什么刪除我的自定義名稱空間是使其與Nginx一起使用的解決方案。
如果有人能弄清楚刪除自定義名稱空間的原因,請隨時對此發表評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.