[英]WebSocket handshake in Node.JS, Socket.IO and Clusters not working
[英]Docker + Node.JS + Socket.IO + Nginx (405 & Bad handshake method)
我有一個帶有react前端和nodeJS / PHP后端的docker容器化應用程序(在不同容器上工作)。 我已經為前端構建和PHP后端成功安裝了帶有中間容器(讓我們使用sencrypt certbot)的https,但是套接字池到nodejs后端存在一些問題。 當socket.io池啟動時,我在POST請求中收到錯誤:
[POST] https://my.domain/socket.io/?EIO = 3&transport = polling&t = MlE0IBv
405不允許
當我試圖通過下一個Nginx構造防止這種情況發生時:
error_page 405 @nodejs;
我在下一條消息中得到了相同的錯誤代碼:
代碼:2消息:“錯誤的握手方法”
我的Nginx配置有一部分(nginx是單獨的docker容器):
upstream node {
ip_hash;
server node:4000; //nodejs container
}
server {
listen 80;
// ...redirect to https
}
server {
listen 443 ssl;
// .... cert's and other settings
// front-end static react build
location / {
try_files $uri /index.html =404;
}
location /static {
try_files $uri @nodejs;
}
location @nodejs {
proxy_pass http://node;
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;
}
// without this string i just got "405 Not Allowed" nginx error page
// with this string i got probably nodejs "Bad handshake method" error
error_page 405 @nodejs;
}
我的app.js服務器代碼:
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const socketRouter = require('./sockets/index');
const app = express();
const server = http.Server(app);
const io = socketIO(server, {origins: '*:*'});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
io.on('connection', socketRouter.bind({}, io));
module.exports = server;
和index.js:
require('dotenv').config();
const app = require('./src/app');
const PORT = process.env.APP_PORT || 4000;
app.listen(PORT);
console.log('Application started on Port ' + PORT);
console.log('APP_ENV ' + process.env.APP_ENV);
問題解決了。 正確的配置是:
location /static {
try_files $uri =404;
}
location /socket.io {
proxy_pass http://node;
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;
add_header Front-End-Https on;
}
error_page 405 @nodejs;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.