2
votes

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:

  • Set the origin like so: io.origins(['*:*']);

  • app.use(function (req, res, next) { res.setHeader( "Access-Control-Allow-Origin", req.header("origin") || req.header("x-forwarded-host") || req.header("referer") || req.header("host") ); res.header( "Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE" ); res.header("Access-Control-Allow-Headers", "X-Requested-With,content-type"); res.setHeader("Access-Control-Allow-Credentials", false); next(); });

  • And also this:

    app.use(cors()); app.options("*", cors());

None of the above worked.

I would appreciate any help.

1
What does getAuthenticationToken return?Take-Some-Bytes
It Returns the object: { Authorization: "Bearer ..." } But I found a workaround! Thanks!Rodolfo

1 Answers

0
votes

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();
  }
});