Socket IO allows CORS request from curl, but not from client application

793 views Asked by At

I am making an application in which i have a node backend, and an angular frontend.

I am using socket.IO to communicate between my client and server.

I was facing CORS issue, which i solved (tried to) as:

const io: SocketIOServer = new SocketIOServer(server, {
  cors: {
    origin: true
  }
}); // only for development

But still, upon making my request from my client app (running in another port) gives me CORS issue.

So i went to my terminal, and made a request with curl,as shown here:

me@Desktop:~$ curl "http://127.0.0.1:5000/socket.io/?EIO=4&transport=polling&t=NV5sBAn"
0{"sid":"jAhPIEEkdy8EY8I_AAAD","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":5000}

This suggests me that curl is being able to access the server, and is not facing CORS issue.

In my client, i am trying to connect to my server as:

socket = io.connect('http://locahost:5000'); // server running at port 5000

Help me with my issue, so i can connect with my server.

Also on a sidenote: If the version of server.io in the app is 3, the curl request to the server is also failing. only upon server.io version 4, the curl request is passing.

The error in firefox if that helps:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://locahost:5000/socket.io/?EIO=4&transport=polling&t=NV5vi1_. (Reason: CORS request did not succeed).

EDIT: my issue is not being able to connect to the server with client. I showed the curl because it was suggested in the socket.io cors configuration webpage.

3

There are 3 answers

0
Himanshu Mittal On BEST ANSWER

Apprrently, the issue was:

 socket = io.connect('http://localhost:5000');

changing this to:

 socket = io.connect('http://127.0.0.1:5000');

worked!! I have no idea why this name was not getting resolved!!

1
Ted Elliott On

Curl does not implement CORS security restrictions, thus it will always be able to connect. You have different ports for your frontend and backend which are considered different CORS origins. So you either need to set your allowed origins correctly on your server and make sure it handles the pre-flight requests, or have the process serving your frontend proxy requests to the backend so that everything is on the same url from the browser’s point of view

0
jfriend00 On

Because socket.io initiates its connection with plain http requests, it is subject to CORs restrictions. CURL does not enforce CORs restrictions (like the browser does) so that's why you don't see it there.

You have a couple options:

  1. You can enable this specific CORs request in your server to permit it.
  2. You can specify the {transports: ['websocket']} option for your socket.io connection in the socket.io client code that initiates the connection. This will tell socket.io to immediately start with a webSocket connection which is not subject to CORs.