Home > database >  Socket.io Node.js CORS ERROR Blocked my req
Socket.io Node.js CORS ERROR Blocked my req

Time:09-30

I'm using node and socket.io to write an application, which gives an error to enable the Cross-Origin Requests.

const io = require("./socket").init(server, {
      cors: {
        origin: "*",
        methods: ["GET", "POST"],
      },
    });

This is my soket.io code...

    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;
  },
};

Help me out from this thanks in advance...

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;
      },
    };

Hope it works for you...

  • Related