Websocket  与 SockJS使用时自动发送/info请求

Websocket 与 SockJS使用时自动发送/info请求

远风 361 2021-11-29

Websocket是个好东西,不多说。SockJS库是Websocket的一种封装实现。

开发使用SockJS的时候经常会发现浏览器会自动发送/info开头的请求,间接也带来了一些诸如跨域配置不起作用的一些问题。

SockJS的https://sockjs.github.io/sockjs-protocol/sockjs-protocol-0.3.3.html#section-26中有这么一段:

Info test: /info
Warning: this is a replacement of /chunking_test functionality from SockJS 0.1.
class InfoTest(Test):
#This url is called before the client starts the session. It's used to check server capabilities (websocket support, cookies requiremet) and to get the value of "origin" setting (currently not used).
But more importantly, the call to this url is used to measure the roundtrip time between the client and the server. So, please, do respond to this url in a timely fashin.

大意呢就是这个是强制性的一个检验,在建立连接之前会向目标服务器发送/info请求,确认服务器是否支持ws以及cookie相关的配置,以及获取origin的配置,更重要的是,这个请求可以用来评估数据传输一轮所需要的时长——或许是为了保证ws传输性能(这个需要进一步确认,纯属个人猜测)。

所以呢,如果涉及到跨域,是肯定需要对类似于/info这种一般的GET/POST等请求进行跨域处理的,而不仅仅只针对WS的连接进行跨域处理,否则会导致ws连接无法进行下去。