0

I trying to establish connection for the first time with web sockets inside my angular app. But its not working and its replacing the url path

My socket service

 public initSocket(): void {
        this.socket = socketIo('http://11.11.11.111/demo-api/status/');
    }

Error

Access to XMLHttpRequest at 'http://11.11.11.111/?EIO=3&transport=polling&t=Meccctccu' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Igor.R
  • 175
  • 4
  • 14
  • Are you using node as a backend ? – Sachin Shah Apr 16 '19 at 13:51
  • @Sachin Shah No – Igor.R Apr 16 '19 at 13:52
  • I'll recommend to use HTML5 - WebSockets instead of socket.io. I was also facing lots of issues while using socket.io in my project then I found two very useful link ref1# https://medium.com/@lwojciechowski/websockets-with-angular2-and-rxjs-8b6c5be02fac, ref2# https://stackoverflow.com/questions/43328451/rxjs-observable-with-websocket HTML5 - WebSockets working like a charm in my project – Sayan Apr 16 '19 at 18:43

2 Answers2

0

You need to enable cors in your backend.

You should read more about what cors mean and enable it in the backend

Arghya Saha
  • 5,599
  • 4
  • 26
  • 48
0

The error you are seeing is quite self-explanatory. You can't connect to another domain via ajax or using web socket if the current domain you are accessing it from does not exist in the allowed origins (Access-Control-Allow-Origin header).

There is a very good explanation of what CORS is on the Mozilla Developer website.

To fix this you will need to add a few headers into the backend you are trying to access which are:

  • Access-Control-Allow-Origin: * (which means allow ANY origin and is not a good idea in production!)
  • Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS, any other you might need
  • Access-Control-Allow-Headers: Accepts, Authorization, Access-Control-Allow-Headers, Access-Control-Request-Headers, Access-Control-Request-Method, DNT, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Content-Range,Range

If you are running your Angular app as an Electron one (for example), you can disable CORS checks: Electron (chromium) disable web security

const win = new BrowserWindow({ webPreferences: { webSecurity: false } });

tftd
  • 16,203
  • 11
  • 62
  • 106