j3f*_*3ff 5 proxy websocket angular-cli angular
我试图使用ng serve --proxy-config proxy.conf.jsonAngular CLI 代理websockets ,但由于我收到此错误,因此无法使其工作:
WebSocket connection to 'ws://stream/connect' failed: Error in connection establishment: net::ERR_NAME_NOT_RESOLVED
以下是我实例化websocket和我的代理配置的方法:
// WebSocket instantiation
const ws = new WebSocket('ws://stream/connect');
// proxy.conf.json
"stream/**": {
"target": "wss://someurl.com:443",
"secure": false,
"ws": true
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?这似乎是可行的,但我不能让它正常工作!
这个封闭的问题https://github.com/angular/angular-cli/issues/6081没有帮助这个stackoverflow答案.
我想到了!如果它可以帮助任何人......
默认情况下,Angular CLI运行应用程序port 4200,代理正在侦听同一个端口...因此我应该这样做:
// websocket instantiation
const ws = new WebSocket('ws://localhost:4200/stream/connect');
// proxy.conf.json
"/stream/*": {
"target": "https://someurl.com:443",
"secure": false,
"ws": true
}
Run Code Online (Sandbox Code Playgroud)
构造函数中的硬编码localhost:4200在WebSocket每个部署环境中都不起作用,因为代理正在侦听的url会有所不同......所以我想出了动态获取位置主机和协议并在WebSocket构造函数中使用它:
// 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`);
Run Code Online (Sandbox Code Playgroud)
和BAM ......瞧!
| 归档时间: |
|
| 查看次数: |
2166 次 |
| 最近记录: |