How to setup a proxy using web sockets and angular CLI - node.js

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.

Related

Proxy Error from backend API to frontend react app

Proxy error: Could not proxy request /api/v1/products from
localhost:3000 to http://192.168.137.1:4000.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ETIMEDOUT).
this error keep on coming.
Frontend -> React
Backend-> Express, nodejs
I faced a similar issue but in the Mac machine. I changed localhost to 127.0.0.1 and that worked for me.
For Windows:
"proxy": {
"/auth/google": {
"target": "localhost:5000"
}
}
For Mac:
"proxy": {
"/auth/google": {
"target": "http://127.0.0.1:5000"
}
}
I just changed "proxy": "http://192.168.137.1:4000" to "proxy": "127.0.0.1:4000" and this worked for me now...
This is done on windows

React, proxy to websocket from package.json get local machine

On AWS ec2 instance I have 2 projects react and nodejs
Due to specific of server I can't connect toc socket by it's ip, but...
I'm trying to use localhost from react package.json proxy, but it's not working. React trying to get :3334 port on my local machine
"proxy": {
"/api": {
"target": "http://localhost:3000"
},
"/socket.io": {
"target": "http://localhost:3334",
"ws": true
}
}
React on port 8000, nodejs on port 3000, socket should be listened on port 3334. I implement connection to nodejs, but with this ws. Can't understand what an I doing wrong
in react:
const socket = openSocket("http://localhost:3334");
On other instance or local machine everything works fine, with ip, but I really need this localhost connection.
Please, help
The problem was that I define in react io socket strictly to localhost. Solution:
const socket = openSocket();

Angular HttpClient fails to proxy

I have a spring boot back-end api and I am trying to call a service for uploading or getting images from angular project. I have a standard proxy.conf.json file:
{
"/api": {
"target": "localhost:8080",
"secure": false,
"logLevel": "debug"
}
}
if my angular service is using Http(HttpModule) everything is ok, but since its deprecated and i want to do it the new way i am trying with HttpClient(HttpClientModule) but in log i am getting :
[HPM] Error occurred while trying to proxy request /upload/ from localhost:4200 to localhost:8080 (ENOTFOUND) (https://nodejs.org/api/errors.html#errors_common_system_errors)
and it is not working. On one try on a linux machine i got the same mistake but with (EINVAL). Can someone guide me what i am doing wrong ? Sorry if the question is stupid there are a few questions like this one but neither of their solutions does not seem to work in my case.
Try to set http protocol in front of the localhost link.
{
"/api": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug"
}
}

How to configure a proxy in Angular CLI

I created a new #angular/cli project and added one http GET call in the root component. Without using a proxy this works fine.
export class AppComponent implements OnInit {
constructor(private http: Http) {}
ngOnInit() {
this.http
.get('https://dog.ceo/api/breeds/list/all')
.map(response => response.json())
.subscribe(data => console.log(data));
}
}
When I try to add the configure as describe in the Angular CLI wiki things go wrong.
My proxy.conf.json file:
{
"/api": {
"target": "https://dog.ceo",
"secure": false
}
}
I changed the URL in the component to /api/breeds/list/all. And I ran ng serve --proxy-config proxy.conf.json
Then I'm gertting Internal Server Error message in my browsers console. And in the terminal where I started ng serve I'm getting this message [HPM] Error occurred while trying to proxy request /api/breeds/list/all from localhost:4200 to https://dog.ceo (EPROTO)
(https://nodejs.org/api/errors.html#errors_common_system_errors)
I have tried several other configuration options and multiple API's. Results are similar.
The complete code is available on GitHub: https://github.com/ErikNijland/angular-cli-proxy-test
Versions used:
#angular/cli: 1.3.0
NodeJS: v8.1.4
Note: I understand that #angular/cli is using Webpack. Which in turn is using http-proxy-middleware.
I think it is happening because of the origin your are asking https from http. This can be solved using a flag in your proxy.
{
"/api": {
"target": "https://dog.ceo",
"secure": false,
"changeOrigin": true
}
}

Reference Socket.io fron Node server in Offline App with Require.js

I am trying to use Socket.io hosted by a Node server. I am using Require.js to manage dependencies. My webapp is Offline capable.
When the webapp is offline, and cannot contact the node server, require.js throws an error because it cannot find the socket.io dependency.
GET http://mikemac.local:8000/socket.io/socket.io.js  require.js:33
Uncaught Error: Script error
http://requirejs.org/docs/errors.html#scripterror
In this case I am not using node/io for the majority of the system, just 'bonus' real time notifications. So The app should run without it.
How can I deal with this? I would like a way to detect that it cannot be found and then disable the socket.io functionality until a connection/refresh attempt.
In your configuration setup fallback to other module and in the fallback indicate that it is offline:
requirejs.config({
enforceDefine: true,
paths: {
socketio: [
'http://mikemac.local:8000/socket.io/socket.io',
//If the CDN location fails, load from this location
'lib/socketoffline'
]
}
});
//socketoffline
define({ offline: true});
//Later
require(['socketio'], function (socketio) {
if (socketio.offline){
// your library did not load:
} else {
// socketio loaded
}
});

Resources