Error during WebSocket handshake: Unexpected response code: 400

websocke偶尔中途断连,重新连接报跨域

问题描述

在开发环境正常使用,测试、生产环境报错,生产环境配置了nginx反向代理。

具体报错截取部分:

Websocket connection to 'ws://*****' faild: Error during WebSocket handshake: Unexpected response code: 400

websocket握手连接报文

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: ws.xx.com
Origin: http://www.xx.com
Set-WebSocket-Ket: xxxxxxxxxxxxxxxx
Sec-WebSocket-Version: 11

和普通http请求的区别是多了两行header:

Upgrade: websocket
Connection: Upgrade

显然它不属于安全的header集合,浏览器会发起“预检请求”,然后根据response header来判断下一步行为,此处我们希望能带上当前域的cookie(包含token),websocket服务端就能正确拿到*.xx.com的cookie,并且完成鉴权工作。

但是websocket本身其实是支持跨域的,本身并没有同源策略。那么按道理不需要做任何操作就应该把xx.com的cookie带到ws.xx.com的websocket网关上面去。

试一下Safari,火狐,不需要配置即可实现。但是在谷歌浏览器就不行,需要专门配置。

解决方案

原项目中使用了Nginx。在配置反向代理时,若需要使用WSS,还需在nginx.conf文件加上websocket的配置如下:

{
    
    
proxy_http_version 1.1;// 告诉nginx使用HTTP/1.1通信协议,这是websocket必须使用的协议
proxy_set_header Upgrade $http_upgrade; //当想使用websocket时,响应http升级请求
proxt_set_header Connection "upgrade"; //当想使用websocket时,响应http升级请求
}

猜你喜欢

转载自blog.csdn.net/m0_38073011/article/details/114839754