CORS error when serving angular with express - node.js

I have 2 server.js files. One of them is inside the backend folder where when I run nodemon server.js on localhost:3000. And I'll start angular with ng serve inside the angular folder and login to my app no problem. Everything works. No CORS issue.
BUT
If I try to run my server.js file in the root directory where express serves my angular build folder. It starts up on localhost:8080, but when I try to login to my app, I get
inside my app.js file I have the following, which should be relevant. Another thing worth noting
is I made a docker version and that version gives me the CORS error too. So it seems to only work when running locally with ng serve and nodemon server.js
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
res.header(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
server.js file in backend folder (localhost:3000 No CORS error)
const app = require("./app");
const debug = require("debug")("node-angular");
const http = require("http");
const mongoose = require("mongoose");
var redis = require("redis");
var env = require("dotenv").config();
const normalizePort = val => {
var port = parseInt(val, 10);
if (isNaN(port)) {
e;
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
};
const onError = error => {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
mongoose
.connect(
"mongodb://" +
process.env.COSMOSDB_HOST +
":" +
process.env.COSMOSDB_PORT +
"/" +
process.env.COSMOSDB_DBNAME +
"?ssl=true&replicaSet=globaldb",
{
auth: {
user: process.env.COSMODDB_USER,
password: process.env.COSMOSDB_PASSWORD
}
}
)
.then(() => console.log("Connection to CosmosDB successful"))
.catch(err => console.error(err));
const onListening = () => {
const addr = server.address();
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
debug("Listening on " + bind);
};
const port = normalizePort(process.env.PORT || "3000");
app.set("port", process.env.PORT || port);
var server = app.listen(app.get("port"), function() {
debug("Express server listening on port " + server.address().port);
});
server.js in root directory (localhost:8080 CORS error)
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
const userRoutes = require("./app/routes/user");
const appRoutes = require("./app/app");
const cors = require("cors");
app.use(morgan('dev'));
app.use(cors({ origin: 'http://localhost:8080' , credentials : true}));var mongoose = require('mongoose');
var path = require('path');
var config = 'mongodb://azure45:azure45#ds133321.mlab.com:33321/azure_chat'
//const app = require("./app");
const debug = require("debug")("node-angular");
var env = require("dotenv").config();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
next();
});
mongoose
.connect(
"mongodb://" +
process.env.COSMOSDB_HOST +
":" +
process.env.COSMOSDB_PORT +
"/" +
process.env.COSMOSDB_DBNAME +
"?ssl=true&replicaSet=globaldb",
{
auth: {
user: process.env.COSMODDB_USER,
password: process.env.COSMOSDB_PASSWORD
}
}
)
.then(() => console.log("Connection to CosmosDB successful"))
.catch(err => console.error(err));
app.use(express.static(__dirname + '/public/dist/glass/'));
//var apiRoutes = require('./app/app')(app, express);
app.use("/api/", appRoutes);
app.use("/api/user", userRoutes);
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname + '/public/dist/glass/index.html'));
});
app.listen(8080);
console.log('Magic happens on port ' + 8080);
const normalizePort = val => {
var port = parseInt(val, 10);
if (isNaN(port)) {
e;
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
};
const onError = error => {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
};
console.log("process.env.COSMODDB_USER");
console.log(env.COSMODDB_USER);
const onListening = () => {
const addr = server.address();
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
debug("Listening on " + bind);
};
Here's the project file structure as a reference. app.js is where all my APIs are.

Try to use Node.js CORS library for CORS.
Something like below.
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors());

With reference to rise's answer:
Add options to cors method:
var corsOptions = {
origin: 'your client url',
optionsSuccessStatus: 200,
}
app.use(cors(corsOptions));

Related

Accessing Node server remotely from React page

I have created a site using Create React App on the frontend and Node express on the back. I then hosted React on IIS and ran Node as a windows service on the backend.
When running the app I set my callback paths in React (REACT_APP_HOST) to "localhost" and in the node my routes are "/routeName". This being said, the first path called is ${REACT_APP_HOST}/sitemap and the receiving path on the server is router.use('/siteMap', (req, res, next) => siteMapController(req, res, next));.
On the local server, using it as a client, this works perfectly. On a remote client (same domain) I am getting a 404 error.
The next step I tried was changing REACT_APP_HOST to "", making the resulting call to "/sitemap". This has stopped the functioning even on localhost.
Here is my code (app.js, sitemap fetch and server.js). Hoping that someone can give me a clue as to where I am going wrong.
//app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser')
var logger = require('morgan');
var cors = require('cors');
var nodeSSPI = require('express-node-sspi');
let routeList = require('./routes/routeList');
let FileLoader = require('./Controllers/FileLoader');
var app = express();
app.use(bodyParser.json({ limit: '400000' }));
app.use(cors({
origin:['http://localhost', 'http://intranet-test', 'http://intranet'],
credentials: true
}));
app.use(express.static(path.join(__dirname,'../public')));
app.options('*', cors()); // include before other routes
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//https://www.npmjs.com/package/yarn
app.use(nodeSSPI({
retrieveGroups: false,
offerBasic: false,
authoritative: true,
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
routeList(app);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log(req.originalUrl);
console.log(req.method)
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
console.log(err);
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
//sitemap fetch
export const fetchInit = () => {
return ({
method: 'GET'
, headers: {
'Content-Type': 'application/json'
}
, credentials: 'include'
})
};
export const Sitemap_Fetch = () => (dispatch) => {
dispatch({
type: ActionTypes.SITEMAP_LOADING
});
var myReq = new Request(`${process.env.REACT_APP_HOST}/siteMap`, fetchInit());//?' + params
return fetch(myReq)
.then((response) => {
// if (response.ok) {
return response;
// }
// else {
// var error = new Error("Error " + response.statusText);
// error.response = response;
// throw error;
// }
},
(error) => {
var err = new Error(error.message);
throw err;
}
)
.then(response => response.json())
.then((data) => {
try {
dispatch({
type: ActionTypes.SITEMAP_LOADED,
payload: data
})
return data;
}
catch (ex) { throw ex }
})
.catch((err) => {
return dispatch({
type: ActionTypes.SITEMAP_FAILED,
payload: err.message
})
});
}
//server.js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('./app');
var debug = require('debug')('node-backend:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort('3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, '0.0.0.0');
server.on('error', onError);
server.on('listening', onListening);
server.on('request',test=>{console.log(test)})
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
console.log(addr)
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
console.log('Listening on ' + bind);
}
Finally I am adding the .env file from my React site
BROWSER=none
SKIP_PREFLIGHT_CHECK=true
REACT_APP_HOST=http://localhost
PORT=80
This works as is. When I change REACT_APP_HOST to nothing it stops functioning.
THanks.
What I have done to solve this is use the serve (https://stackoverflow.com/a/49209041/2242131) command from a simple batch file and run my node backend from another batch. Then in React I created a constant called "hostname" which I set to ${window.location.hostname}:3000. This is now consistently serving my pages the necessary data.

WebSocket with Express - Invalid WebSocket frame: invalid UTF-8 sequence

I'm building a web application using HTTPS, Express, Socket.io, and WebSocket. Currently Express is using port 3000. In order to use the same port of WebSocket as 3000 port, I wrote the code as follows.
app.js
const path = require('path');
const express = require('express');
const app = express();
const mainRouter = require('./routes/main/main');
// Middleware
...
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'res')));
app.use('/', mainRouter);
// 404 error handler
app.use((req, res) => {
logger.error(`404 Page not found`);
res.status(404).send('404 Page not found');
});
module.exports = app;
bin/www
const fs = require('fs');
const path = require('path');
const app = require('../app');
const https = require('https');
const options = {
key: fs.readFileSync(path.resolve(__dirname, '../config/ssl/localhost-key.pem')), // Private key
cert: fs.readFileSync(path.resolve(__dirname, '../config/ssl/localhost.pem')), // Certificate
};
const server = https.createServer(options, app);
const io = require('socket.io')(server);
const WebSocket = require('../public/js/websocket');
const normalizePort = (value) => {
const port = parseInt(value, 10);
if(isNaN(port)) {
return value;
}
if(port >= 0) {
return port;
}
return false;
};
const port = normalizePort(process.env.PORT || 3000);
// Setting port
app.set('port', port);
const onError = (err) => {
if(err.syscall !== 'listen') {
throw err;
}
const bind = typeof(port) === 'string' ? `Pipe ${port}` : `Port ${port}`;
switch(err.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
};
const onListening = () => {
const address = server.address();
const bind = typeof(address) === 'string' ? `Pipe ${address}` : `Port ${port}`;
};
...
WebSocket(server);
server.listen(port, '0.0.0.0');
server.on('error', onError);
server.on('listening', onListening);
public/js/websocket.js
const ws = require('ws');
module.exports = function WebSocket(server) {
const wss = new ws.Server({ server : server });
wss.on('connection', (ws, req) => {
ws.on('message', (data) => {
ws.send(data);
console.log(data);
});
});
wss.on('listening', () => {
console.log('listening..');
});
};
routes/main/main.js
const router = require('express').Router();
const { v4 : uuidv4 } = require('uuid');
router.get('/', (req, res) => {
res.redirect(`/${uuidv4()}`);
});
router.get('/:room', (req, res) => {
res.render('main/main', { room: req.params.room });
});
module.exports = router;
After configuring the server as above, if you connect to https://localhost:3000 after npm start, the following error occurs.
Error: Invalid WebSocket frame: invalid UTF-8 sequence ... code: 'WS_ERR_INVALID_UTF8', [Symbol(status-code)]: 1007
I don't understand why this error occurs. Also, how can I fix the code to fix the error?

After refresh "Cannot set headers after they are sent to the client"

I am using express js, mongoose and ejs as templates.
When I refresh my page, in second or third try, I get this error.
Here is my app.js :
{consts..}
var index = require('./routes/index.js');
var users = require('./routes/users.js');
app.set("port", ("2401"));
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', index);
app.use('/users', users);
var port = '2401';
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('server started on port : ' + app.get('port'));
}
users router :
{consts..}
router.get('/login', function (req, res) {
users.getLogin(req, res);
});
router.post('/login', [
check('email')
.isEmail().withMessage('Please enter a valid email address')
.trim()
.normalizeEmail(),
check('terms', 'Please accept our terms and conditions').equals('yes'),
],
function (req, res) {
users.postLogin(req, res);
});
module.exports = router;
and controller :
usersController.getLogin = function (req, res) {
const connector = mongoose.connect(conStr, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('open', function (ref) {
categories.find(function (err, cats) {
if (err) {
console.log("Error:", err);
}
else {
return res.render("../views/login.ejs", {
_: _,
categories: cats
});
}
});
});
}
index router :
var express = require('express');
var router = express.Router();
var index = require("../controllers/indexController.js");
router.get('/', function (req, res) {
index.list(req, res);
});
module.exports = router;
index controller:
var mongoose = require("mongoose");
var categories = require("../models/categories.js");
var _ = require("underscore");
var indexController = {};
indexController.list = function (req, res) {
const connector = mongoose.connect(conStr, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('open', function (ref) {
categories.find(function (err, cats) {
if (err) {
console.log("Error:", err);
}
else {
console.log("indexe geldi");
return res.render("../views/index.ejs", {
_: _,
categories: cats,
sess: req.session
});
}
})
})
};
module.exports = indexController;
I tried almost everything but still no progress. Can it be about usage of "next()" ?
I also tried the hole router get / post functions with next, mongoose find functions with exec().
The issue is that you're opening a connection to mongo in every route and:
mongoose.connection.on('open' is firing for past requests, requests that are already finished, that's why you're getting Cannot set headers after they are sent to the client.
Move the mongoose.connect & the listener outside of each route.
usersController.getLogin = function (req, res) {
categories.find(function (err, cats) {
if (err) {
console.log("Error:", err);
return res.status(500).send('error');
}
else {
return res.render("../views/login.ejs", {
_: _,
categories: cats
});
}
});
}

How to deploy nodejs and express to AWS EC2 Instance

I have a MEAN application that needs deployment and I chose to deploy it on AWS Linux AMI but I have some problems deploying it.
Based on the tutorials I read so far every nodejs and express contains html pages.
How do I deploy it without html pages on it? like if they go to the domain they just see a blank page?
I know I can just empty an html file but I any other solutions?
here's my server.js
const http = require("http");
const debug = require("debug")("sales-and-inventory");
const app = require("./app");
// normalizePort() makes sure that the port is a valid number data type
const normalizePort = val => {
var port = parseInt(val, 10);
if (isNaN(port)) {
// isNot-a-Number
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
};
// checks the type of error occured
const onError = error => {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
};
// just logging
const onListening = () => {
const addr = server.address();
const bind = typeof port === "string" ? "pipe " + port : "port " + port;
debug("Listening on " + bind);
};
// set a config for the express environment & config for the port
const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
const server = http.createServer(app);
// registered on this listeners on the function above
server.on("error", onError);
server.on("listening", onListening);
// start server
server.listen(port);
here's the app.js
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const authRoutes = require("../routes/auth.route");
const userRoutes = require("../routes/user.route");
const customerRoutes = require("../routes/customer.route");
const vendorRoutes = require("../routes/vendor.route");
const salesRoutes = require("../routes/sales-order.route");
const purchaseRoutes = require("../routes/purchase-order.route");
const inventoryRoutes = require("../routes/inventory.route");
const transferRoutes = require("../routes/transfer.route");
const paymentRoutes = require("../routes/payment.route");
const app = express();
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);
mongoose.connect(process.env.ATLAS_CONNECTION_STRING, { useNewUrlParser: true })
.then(() => {
console.log("Connected to Atlas");
})
.catch(err => {
if (err) {
console.log(err);
}
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// CORS
app.use((req, res, next) => {
// allows any domain to access our resources
res.setHeader("Access-Control-Allow-Origin", "*");
// allows domain with a certain set of headers
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, Authorization"
);
// allows http type of requests
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
res.header('Content-Security-Policy', 'img-src "self"');
next();
});
app.use("/api/auth", authRoutes);
app.use("/api/user", userRoutes);
app.use("/api/customer", customerRoutes);
app.use("/api/vendor", vendorRoutes);
app.use("/api/sales", salesRoutes);
app.use("/api/purchase", purchaseRoutes);
app.use("/api/inventory", inventoryRoutes);
app.use("/api/transfer", transferRoutes);
app.use("/api/payment", paymentRoutes);
module.exports = app;
After launching the EC2 Instance, you can go ahead with the setting SSH on your machine if you are using windows go for PUTTY.
Follow this tutorial for deploying NodeJS Application once you are logged into instance.
https://www.youtube.com/watch?v=tasoWTGM1hA
before deploying Make sure add Security group to EC2 instance and add the role of HTTP, HTTPS with any IP address I mean 0.0.0.0 and any port :0

Can't establish a connection to the server with websockets

I am doing a MEAN stack application. To communicate between the client and the server I use some HTTP requests and websockets.
On the localhost it works fine.
But then, when I try to deploy the application from localhost to a specific server, the websockets are not working anymore. However, http requests work fine.
I got this error:
Firefox can't establish a connection to the server at
ws://138.250.31.29:3000/socket.io/?userId=5b7c030dca40486dabaafaaf&EIO=3&transport=websocket&sid=oEcoYYbhD4ighJC0AAAB.
I didn't succeed to have more information about this error.
In order to establish the connection I have two files on Node.JS:
APP.JS
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const logger = require("morgan");
const favicon = require("serve-favicon");
const cors = require("cors");
require("./models/db");
require("./config/passport");
const passport = require("passport");
const apiRouter = require("./routes/index");
const corsOptions = {
origin: "*",
optionsSuccessStatus: 200
};
const app = express();
app.use(logger("dev"));
app.use(express.json({ limit: "1gb" }));
app.use(express.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(cors(corsOptions));
app.use("/api", apiRouter);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
// error handlers
// Catch unauthorised errors
app.use(function(err, req, res, next) {
if (err.name === "UnauthorizedError") {
res.status(401);
res.json({ message: err.name + ": " + err.message });
}
});
module.exports = app;
WWW
!/usr/bin/env node
/**
* Module dependencies.
*/
const app = require("../app");
const debug = require("debug")("sorfml:server");
const http = require("http");
const socketIO = require("socket.io");
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Bind the socket.IO with the http server
*/
const io = socketIO(server);
io.origins("*:*");
clientsList = {};
/**
* Socket connection
*/
io.on("connection", socket => {
console.log("Client connected " + socket.id);
socket.user_id = socket.handshake.query.userId;
clientsList[socket.handshake.query.userId] = socket;
socket.on("disconnect", () => {
delete clientsList[socket.user_id];
console.log("Client disconnected: " + socket.id);
});
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
const port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "Pipe " + port : "Port " + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
console.log("Listening on " + bind);
}
On the client side:
import * as io from "socket.io-client";
private socket;
this.socket = io("http://138.250.31.29:3000", { query: "userId=" + userId });
this.socket.on("sendNotification", data => {
// Do a function
});
this.socket.on("deleteNotificationFromAuthor", data => {
// Do a function
});
You are using http instead of ws on client side,
this.socket = io("ws://138.250.31.29:3000", { query: "userId=" + userId });
FYI: In case you didn't knew, both http and ws port may be the same as the w3 standard. You should use ws protocol to create a web socket connection
Hope that helps.

Resources