Socket.IO version - 4.4.1
Server
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const cors = require("cors");
const io = new Server(server, {
cors,
});
const PORT = 3000;
app.use(cors());
io.on("connection", (socket) => {
console.log("A user connected :)");
socket.on("msg", console.log);
socket.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
});
server.listen(PORT, () => {
console.log("listening on *:" PORT);
});
HTML
Inside body
<script
src="https://cdn.socket.io/4.4.1/socket.io.min.js"
></script>
<script>
// socket.io
console.log("Connecting..")
const socket = io("http://localhost:3000")
socket.on("connect", () => {
console.log(socket.connected); // true
});
</script>
There is no error on either client or server, but still i am not able to connect to the server.
CodePudding user response:
If you change this:
const io = new Server(server, {
cors,
});
to this:
const io = new Server(server);
Then, your code starts working for me. So, something is wrong with how you're trying to use cors with socket.io. FYI, if you change the client to always use a webSocket as the transport, then you won't need CORS for your socket.io connection because a websocket connection is not subject to same origin restrictions.
const socket = io("http://localhost:3000", {transports: ["websocket"]});
By default a socket.io connection starts with http polling (which is subject to same origin restrictions) and then switching to a websocket after a few http requests.