Angular CLI: Proxy websocket with proxy.conf.json

2020-08-23 04:42发布

问题:

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.

回答1:

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:

// websocket instantiation
const ws = new WebSocket('ws://localhost:4200/stream/connect');

// proxy.conf.json
"/stream/*": {
  "target": "https://someurl.com:443",
  "secure": false,
  "ws": true
}

Hardcoding localhost:4200 in the WebSocket 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 the WebSocket constructor:

// set ws protocol when using http and wss when using https
const protocol = window.location.protocol.replace('http', 'ws');
// get location host
const host = window.location.host;
// websocket instantiation
const ws = new WebSocket(`${protocol}//${host}/stream/connect`);

And BAM ... voilà!!