Home > Net >  https://www.example.com and https://example.com socket.io connection problem
https://www.example.com and https://example.com socket.io connection problem

Time:02-06

How do I get both https://example.com and https://www.example.com for endpoints to connect? socket.io connect no problem at htttps://example.com but not https://www.example.com

my server looks like

const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "https://www.example.com:3000",
    methods: ["GET", "POST"],
    allowedHeaders: ["my-custom-header"],
    credentials: true
  }});

and my client endpoint looks like this

const ENDPOINT = 'https://example.com/';

CodePudding user response:

Configure your DNS to point both example.com and www.example.com to the same host IP address and then support both domains with your cors configuration. Then, either URL will go to the same host.

You can avoid cors entirely if you configure socket.io to start immediately with a webSocket, not with the http polling that it usually starts with. You can do that in the client by adding the transports: ['websocket'] option to the client connect.

And, your custom header was probably blocking CORs and requiring pre-flight permission. CORs has two levels, simple and not-simple. When you add a custom header, you force CORs into the not-simple route where it requires preflight which is probably more than the built-in socketio cors features will handle.

  •  Tags:  
  • Related