如何使用网络套接字和 angular CLI 设置代理

How to setup a proxy using web sockets and angular CLI

我有一个使用 angular CLI 构建的简单网络应用程序。我希望它使用网络套接字与后端通信。我已经编写了后端并使用服务器可以在套接字上发送和接收的简单 index.html 页面进行了测试。

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

proxy.conf.json

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

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

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

现在我有一个服务,它只是尝试打开一个套接字并发送一个我希望看到后端记录的固定字符串。

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 CLI web pack 服务器中,我收到以下消息。

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)

是否支持网络套接字,还是我犯了一个愚蠢的错误? 谢谢

我通过反复试验设法弄明白了。我查看了后端项目中工作的基本 index.html 页面的控制台。这个后端项目基本上是 socket.io 网站上的聊天服务器演示应用程序。我注意到当它打开网络套接字时,url 看起来像下面这样:

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

所以回到 angular CLI 项目,我修改了我的代理配置以包含 /socket.io/ 部分并添加了一个通配符。

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

宾果!现在,当构建服务时,它会打开套接字并发出一条消息,我可以看到该消息已记录在后端。