node.js - WebSocket握手时跨域WebSocket连接失败: Unexpected response code: 400

标签 node.js nginx websocket socket.io

我正在尝试在 Node js 应用程序中使用 socket.io。我的应用程序位于子域上,前端在该域的 www 版本上运行。

不能在同一个域上运行前端和 Node js 服务。

从客户端到服务器来回发送数据似乎有效。我已经通过两种方式发送了数据,效果很好。

但是,在浏览器的控制台中我收到以下错误。

WebSocket connection to 'wss://subdomain.domain.com/socket.io/?EIO=3&transport=websocket&sid=6bNHWyXcCdlMI0HHAAAB' failed: Error during WebSocket handshake: Unexpected response code: 400

我的 Nginx 配置如下所示:

# HTTP - redirect all requests to HTTPS:
server {
        listen 80;
        listen [::]:80 default_server ipv6only=on;
        return 301 https://$host$request_uri;
}

# HTTPS - proxy requests on to local Node.js app:
server {
        listen 443;
        server_name subdomain.domain.com;

        ssl on;
        # Use certificate and key provided by Let's Encrypt:
        ssl_certificate /etc/letsencrypt/live/subdomain.domain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/subdomain.domain.com/privkey.pem;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers '*******';

        # Pass requests for / to localhost:3000:
        location / {
                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_pass http://localhost:3000/;
                proxy_ssl_session_reuse off;
                proxy_set_header Host $host;
                proxy_cache_bypass $http_upgrade;
                proxy_redirect off;
                proxy_http_version 1.1;
                proxy_set_header Connection "upgrade";

       }
}

客户端和 Node js 都使用 https。

有谁知道导致此问题的原因以及如何解决它?

谢谢

最佳答案

您似乎忘记了升级 header 。如果您想使用 Nginx 作为 WebSocket 的反向代理,则这是必需的。

如前所述here ,尝试再添加一个 header : proxy_set_header 升级 $http_upgrade;

关于node.js - WebSocket握手时跨域WebSocket连接失败: Unexpected response code: 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41742440/

相关文章:

node.js - 指定 console.trace 深度

javascript - 如何强制检查由 node.js 服务器处理的 http 请求的查询字符串中的特定参数序列?

linux - 用于开发和生产的不同 url

javascript - 重新连接到同一个 Websocket

javascript - 字符串转换为 undefined/null/number/boolean

eclipse - Eclipse 中的 node.js - 大多数人使用哪些插件?

node.js - Meteor 忘记密码邮件不发送

node.js - 你能从 Stud > HAProxy > nginx 获取 X-forwarded-for 吗?

node.js - 通过工作进程向客户端返回响应的 node.js 模式是什么

javascript - 浏览器同步关闭websocket