Alen
Alen

Reputation: 35

How to fix this CORS issue in socket.io?

I am trying to connect to a remote server with socket.io, but I am having some problems. I am getting this error: The value of the Access-Control-Allow-Credentials header in the response is ' ' which must be 'true' when the request's credentials mode is 'include'

OK, so here is the code:

Server

var server = require('http').createServer();

const io = require("socket.io")(server, {
  cors: {
    origin: "my URL",
    methods: ["GET", "POST"],
    credentials: false
  }
});


io.sockets.on('connection', function(socket) {
    console.log("Client has connected!");
});

console.log ('Server started.');
server.listen(3000);

Here is the client code:

var socket = io.connect("https://persistent-gentle-banon.glitch.me", {
  withCredentials: false
});

How can I solve this and get it to connect?

Thanks for any help!

Upvotes: 1

Views: 6220

Answers (2)

STEVE  K.
STEVE K.

Reputation: 919

According to this link https://socket.io/docs/v4/server-instance/#serverengine , you should use io.engine initial_headers and headers events to set cors headers simply, this should work with socket.io v4+.

import { createServer } from "http";
import {Server} from  'socket.io';

const server = createServer(app);
const io = new Server(server);

io.engine.on("initial_headers", (headers, req) => {
  headers["Access-Control-Allow-Origin"] = "http://localhost:4200";
});

io.engine.on("headers", (headers, req) => {
  headers["Access-Control-Allow-Origin"] = "http://localhost:4200"; // url to all
});

server.listen(3000);

Upvotes: 1

Amir Doreh
Amir Doreh

Reputation: 1439

i had the same problem, i was using express and i was able to solve it by

var cors = require("cors");
const corsOptions = {
  origin: "*",
  optionsSuccessStatus: 200
};
const io = require("socket.io")(server, {
  cors: {
    origin: "*",
    methods: ["PUT", "GET", "POST", "DELETE", "OPTIONS"],
    credentials: false
  }
  // transports: ['websocket']
});

app.use(cors(corsOptions));

Upvotes: 3

Related Questions