1
votes

I have cors error while using Socketio v3 the app is on React backed by Nodejs

Server Side Codes:

var server = http.createServer(app);
var port = process.env.PORT || '3000'
const io = require("socket.io")(server,{
cors: {
  origin: "*:*",
  methods: ["PUT", "GET", "POST", "DELETE", "OPTIONS"],
  allowedHeaders:["secretHeader"],
  credentials: true
}
})

Client Side Connecting code:

const SOCKET_URL = "https://fakeurl.org";
socket.current = io(`${SOCKET_URL}`,{
      secretHeader:{
        "Access-Control-Allow-Headers": "*"
      }
    });

And i got the following error:

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

1
Do you try to add Access-Control-Allow-Origin into allowedHeaders? - chonnychu
remove secretHeader option in client side, and instead of it, use "extraHeaders" - wangdev87

1 Answers

2
votes

Refer to Socket.io Handling CORS.

// server-side
const io = require("socket.io")(server,{
cors: {
  origin: "*",
  methods: ["PUT", "GET", "POST", "DELETE", "OPTIONS"],
  allowedHeaders:["secretHeader"],
  credentials: true
}
})
// client-side
const SOCKET_URL = "https://fakeurl.org";
socket.current = io(`${SOCKET_URL}`,{
      withCredentials: true,
      extraHeaders: {
          "secretHeader": "secret value"
      }
    });