Home > Net >  Getting CORS EROOR on socket.io and express(node.js)
Getting CORS EROOR on socket.io and express(node.js)

Time:10-12

Socket.io and Node.js (express.js) getting CORS error

 let io;
    module.exports = {
      init: (httpServer) => {
        io = require("socket.io")(httpServer);
        return io;
      },
      getIO: () => {
        if (!io) {
          throw new Error("Socket.io not inittialized");
        }
    return io;
  },
};

CodePudding user response:

Try this code in socket js you have to send

cors: {
       origin: "*",
       methods: ["GET", "POST"],
      }, 

Cors in the socket also to avoid this error

  let io;
    module.exports = {
      init: (httpServer) => {
        io = require("socket.io")(httpServer, {
          cors: {
            origin: "*",
            methods: ["GET", "POST"],
          },
        });
        return io;
      },
      getIO: () => {
        if (!io) {
          throw new Error("Socket.io not inittialized");
        }
        return io;
      },
    };
  • Related