简体   繁体   中英

How to setup a proxy using web sockets and angular CLI

I have a simple web app built using the angular CLI. I want it to communicate with a backend using web sockets. I have the backend already written and have tested with a simple index.html page that the server can send and receive on sockets.

In my angular-cli project I have setup a proxy config file to setup a proxy to the backend.

proxy.conf.json

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

Then start the server with the following.

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

For now I have a service that simply attempts to open a socket and send a fixed string which I'm expecting to see logged by the backend.

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!');
   }

}

Note: I've had several go's at this with and without the /sock part of the url.

I start both servers. Get no console errors in the browser. But in the angular CLI web pack server I get the following messages.

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)

Are web sockets supported or have I made a silly mistake? Thanks

I managed to figure it out with a bit of trial and error. I looked at the console for the basic index.html page that works within the backend project. This backend project is basically the chat server demo application on the socket.io website. I noticed that when it opens up the web socket the url looks like the following:

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

So back in the angular CLI project I modified my proxy config to include the /socket.io/ part plus also added a wildcard.

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

Bingo! Now when the service is constructed it opens the socket and emits a message which I can see logged in the backend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM