2

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.

2
  • What does getAuthenticationToken return? Commented Oct 7, 2020 at 3:57
  • It Returns the object: { Authorization: "Bearer ..." } But I found a workaround! Thanks! Commented Oct 7, 2020 at 12:36

1 Answer 1

1

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(); } }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.