28

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.

2 Answers 2

54

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à!! 🎊 🎉 👏

Sign up to request clarification or add additional context in comments.

4 Comments

Why is the target switched back to https rather than wss in this answer?
"ws": true and target: ws:// ... is the key.
"ws": true has saved my last hairs.
To guys wondering if this works now too! As of angular 14 @Stefan 's solution works like a charm.
6

What helped me having both web socket stream and ASP.Net Core controllers was having both "target": "http:yourAppUrl:portToProxyTo" and "ws": true set up in proxy.config.js file.

{
    "/": {
        "target": "http://someurl.com:443",
        "secure": false,
        "ws": true,
        "logLevel": "debug"
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.