我正在制作一个应用程序,其中有一个节点后端和一个角度前端。
我正在使用 socket.IO 在我的客户端和服务器之间进行通信。
我正面临 CORS 问题,我将其解决(尝试)为:
const io: SocketIOServer = new SocketIOServer(server, {
cors: {
origin: true
}
}); // only for development
但是,从我的客户端应用程序(在另一个端口运行)提出请求后,我仍然遇到了 CORS 问题。
所以我去了我的终端,并用 curl 提出了一个请求,如下所示:
me@Desktop:~$ curl "http://127.0.0.1:5000/socket.io/?EIO=4&transport=polling&t=NV5sBAn"
0{"sid":"jAhPIEEkdy8EY8I_AAAD","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}
这表明我 curl 能够访问服务器,并且没有面临 CORS 问题。
在我的客户端中,我试图连接到我的服务器:
socket = io.connect('http://locahost:5000'); // server running at port 5000
帮助我解决我的问题,以便我可以连接到我的服务器。
另附注:如果应用程序中 server.io 的版本为 3,则对服务器的 curl 请求也会失败。只有在 server.io 版本 4 上,curl 请求才会通过。
如果有帮助,Firefox中的错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://locahost:5000/socket.io/?EIO=4&transport=polling&t=NV5vi1_. (Reason: CORS request did not succeed).
编辑:我的问题是无法使用客户端连接到服务器。我展示了 curl,因为它是在 socket.io cors 配置网页中建议的。