How can I use CORS with a socket.io server not built on top of a HTTP server
I'm trying to write a server running under nodejs that is just supposed to be a socket server; not supposed to accept http requests at all. Here's how I am setting it up:
import { Server as ServerSocket } from 'socket.io';
import { ClientToServerEvents, ServerToClientEvents } from './types';
const server = new ServerSocket<
ClientToServerEvents,
ServerToClientEvents>({cors:{
origin: "*"
}});
server.on('connection', (client) => {
console.log('got connection');
});
server.listen(55555);
server.engine.on("initial_headers", (headers:unknown, req:unknown) => {
if (typeof headers === 'object' && headers) {
Object.assign(headers, {"Access-Control-Allow-Origin": "*"});
}
});
server.engine.on("headers", (headers:unknown, req:unknown) => {
if (typeof headers === 'object' && headers) {
Object.assign(headers, {"Access-Control-Allow-Origin": "*"});
}
});
As you can see, I have tried three ways to set up CORS (from random web pages, hacked to allow T开发者_开发问答ypeScript to be happy), but none of them work. The client (a React-based web page on firefox) is unable to connect. It uses:
import { Socket, io } from 'socket.io-client';
...
this.socket = io(':55555');
I always get:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:55555/socket.io/?EIO=4&transport=polling&t=OJgOc80. (Reason: CORS request did not succeed). Status code: (null).
Indeed this happens even if the server isn't running. It seems to be blocked on the client. Is it because socket.io-client is still using http?
精彩评论