Home > Net >  Can't run Socket.io server, TypeError: Server is not a constructor
Can't run Socket.io server, TypeError: Server is not a constructor

Time:01-20

I'm trying to run socket.io, with express Js. Below is my code of server.js

const express = require("express");
const app = express();
const http = require("http");
const cors = require("cors");
const Server = require("socket.io");

app.use(cors());
 const server = http.createServer(app);

const io = new Server(server, {
  cors: {
    origin: "http://localhost:3000",
    methods: ["GET", "POST"],
  },
});

io.on("connection", (socket) => {
  console.log(`User connected: ${socket.id}`);
  socket.on("Disconnect", () => {
    console.log(`User disconnected: ${socket.id}`);
  });
});

server.listen(3000, () => {
  console.log("SERVER WALKING");
});

And after running nodemon server.js via scripts.

I get this error

const io = new Server(server, {
           ^

TypeError: Server is not a constructor
    at Object.<anonymous> (Path:10:12)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Module._load (node:internal/modules/cjs/loader:827:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

Node.js v18.0.0
[nodemon] app crashed - waiting for file changes before starting...

Can anyone help me to point out what I'm doing wrong in this scenario.

I tried removing and re-adding node_modules, both with npm and yarn but still showing same error.

CodePudding user response:

Use const { Server } = require("socket.io"); to import the Server class in socket.io library.

CodePudding user response:

Try this:

const express = require("express");
const app = express();
const http = require("http");
const cors = require("cors");
app.use(cors());
const server = http.createServer(app);
const io = require("socket.io")(server, {
    cors: {
      origin: ["http://localhost:3000"],
      methods: ["GET", "POST"],
    },
  });
io.on("connection", (socket) => {
  console.log(`User connected: ${socket.id}`);
  socket.on("Disconnect", () => {
    console.log(`User disconnected: ${socket.id}`);
  });
});

server.listen(3000, () => {
  console.log("SERVER WALKING");
});

  • Related