通过 web-socket 处理 CORS 通信

Posted

技术标签:

【中文标题】通过 web-socket 处理 CORS 通信【英文标题】:Handling CORS in communication through web-sockets 【发布时间】:2021-03-12 04:49:25 【问题描述】:

我正在开发一个客户端和服务器应用程序,通过 web-socket 进行通信,发现仅在 web-socket 上处理 CORS 不会引发任何额外的 CORS 问题,而不是在服务器端本身处理 CORS。

在解决问题之前,客户端的错误是:

Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NOOM0wp' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

响应对象上没有“Access-Control-Allow-Origin”标头,仅当我在服务器端处理 CORS 时才会出现。

但是,在客户端我得到一个错误:

GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=NOONjI6 net::ERR_CONNECTION_REFUSED

我想这是一个非常简单的问题,仍然会非常感谢您的解释。

【问题讨论】:

【参考方案1】:

使用cors 配置。

请参阅Handling CORS。

var express = require('express')
var app = express()
var app = express()
var server = require('http').createServer(app)
var io = require('socket.io')(server, 
  cors: 
    origin: "*" // add your own origin, or '*' for any origins allow.
  
)

【讨论】:

以上是关于通过 web-socket 处理 CORS 通信的主要内容,如果未能解决你的问题,请参考以下文章

Web-Socket

在没有弹簧身份验证的情况下通过 web-socket 多次回复

web-socket php中的问题

处理离子中的CORS问题

Python web-socket解释(读取)数据

使用 Spring 3.0.4 启用 Cors