Rodolfo
Rodolfo

Reputation: 83

Socket.io , NodeJS and ReactJS CORS error

As a starter, I have read a bunch of question concerning the same issue.

When I open the connection with the socket via React client the normal way, just the URL as parameter, I don't get this error, connection established.

But when I do this:

const io = ioClient(webSocketUrl, {
  transportOptions: {
    polling: {
      extraHeaders: getAuthenticationToken()
    }
  }
});

The request return a CORS error everytime.

I have tried to:

None of the above worked.

I would appreciate any help.

Upvotes: 2

Views: 862

Answers (1)

Rodolfo
Rodolfo

Reputation: 83

Found the answer!

For anyone with the same problem, this is how I've done it:

const io = require("socket.io")(server, {
  handlePreflightRequest: (req, res) => {
      const headers = {
          "Access-Control-Allow-Headers": "Content-Type, Authorization",
          "Access-Control-Allow-Origin": req.headers.origin, //or the specific origin you want to give access to,
          "Access-Control-Allow-Credentials": true
      };
      res.writeHead(200, headers);
      res.end();
  }
});

Upvotes: 1

Related Questions