如何使用Web套接字和angular度CLI来设置代理

我有一个使用angular度CLI构build的简单的Web应用程序。 我希望它使用networking套接字与后端进行通信。 我已经编写了后端,并用一个简单的index.html页面进行了testing,服务器可以在套接字上发送和接收数据。

在我的angular-cli项目中,我已经设置了一个代理configuration文件来设置代理到后端。

proxy.conf.json

{ "/sock": { "target": "http://localhost:3000", "changeOrigin": true, "ws": true, "logLevel": "debug" } } 

然后使用以下命令启动服务器。

 ng serve --proxy-config proxy.conf.json 

现在我有一个服务,只是试图打开一个套接字,并发送一个固定的string,我期待看到后台logging。

 import { Injectable } from '@angular/core'; import * as io from 'socket.io-client'; @Injectable() export class ChatService { private socket: any; constructor() { this.socket = io({ 'path': '/sock' }); this.socket.emit('chat message', 'Hello World from browser!'); } } 

注意:我已经有几次去了这个url的/ sock部分。

我启动两台服务器。 在浏览器中没有控制台错误。 但是在angular度CLInetworking包服务器中,我收到以下消息。

 10% building modules 2/2 modules 0 active[HPM] Proxy created: /sock -> http://localhost:3000 [HPM] Subscribed to http-proxy events: [ 'error', 'close' ] [HPM] GET /sockjs-node/530/z1z3teld/websocket -> http://localhost:3000 [HPM] Upgrading to WebSocket [HPM] Error occurred while trying to proxy request /sockjs-node/530/z1z3teld/websocket from localhost:4200 to http://localhost:3000 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors) 

Web套接字是支持还是我犯了一个愚蠢的错误? 谢谢

我设法找出了一些试验和错误。 我查看了在后台项目中工作的基本index.html页面的控制台。 这个后端项目基本上是socket.io网站上的聊天服务器演示应用程序。 我注意到,当它打开networking套接字的url如下所示:

 http://localhost:3000/socket.io/EIO=3&transport=websocket&sid=wTvdQTclHXJSUmAmAAAA 

所以回到angularCLI项目中,我修改了我的代理configuration,包括/socket.io/部分,还加了一个通配符。

 { "/sock/*": { "target": "http://localhost:3000/socket.io/", "ws": true, "logLevel": "debug" } } 

答对了! 现在,当构造服务时,它打开套接字并发出一条消息,我可以看到在后端logging。