I am trying to proxy websockets using ng serve --proxy-config proxy.conf.json
with Angular CLI but could'nt get it to work as I am getting this error:
WebSocket connection to 'ws://stream/connect' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED
Here is how I instantiated the websocket and my proxy configuration:
// WebSocket instantiation
const ws = new WebSocket('ws://stream/connect');
// proxy.conf.json
"stream/**": {
"target": "wss://someurl.com:443",
"secure": false,
"ws": true
}
Am I missing something? It seems to be doable but i can't get it to work correctly!
This closed issue https://github.com/angular/angular-cli/issues/6081 did not helped neither did this stackoverflow answer.
I figured it out! If it can help anyone...
By default Angular CLI runs the application on
port 4200
and proxy is listening on that same port... therefore I should do:Hardcoding
localhost:4200
in theWebSocket
constructor wouldn't work in every deployed environment because the url on which the proxy is listening would differs... so I came up with getting the location host and protocol dynamically and used it in theWebSocket
constructor:And BAM ... voilà!!