Can't establish a connection to the server with websockets - node.js

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.

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.

Express Server continuously throws 404 error

I keep getting these errors.
Here's some of my code.
bin/www
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('server:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* 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) {
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();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var eventsRouter = require('./routes/events');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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')));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested, Content-Type, Accept, Authorization');
res.setHeader(
'Access-Control-Allow-Methods',
'GET, POST, PATCH, DELETE, OPTIONS')
next();
});
app.use('/dashboard', eventsRouter);
app.use('/user', usersRouter);
// 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');
});
mongoose.connect('// this is good just deleted for post')
.then(() => {
console.log("Connected to database!");
})
.catch(() => {
console.log("Connection failed.")
});
module.exports = app;
users.js
const express = require('express');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const router = express.Router();
const User = require('../models/user');
router.post('/signup', (req, res, next) => {
bcrypt.hash(req.body.password, 10)
.then(hash => {
const user = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
userName: req.body.userName,
email: req.body.email,
password: hash
});
user.save()
.then(result => {
res.status(201).json({
msg: "User Created",
rslt: result
});
})
.catch(err => {
res.status(500).json({
err: err
});
});
});
});
router.post("/login", (req, res, next) => {
let fetchedUser;
User.findOne({ email: req.body.email })
.then(user => {
if (!user) {
return res.status(401).json({
msg: "Auth Failed."
});
}
fetchedUser = user;
return bcrypt.compare(req.body.password, user.password)
})
.then(result => {
if (!result) {
return res.status(401).json({
msg: "Auth Failed."
});
}
const token = jwt.sign(
{ email: fetchedUser.email, userId: fetchedUser._id },
// ,
{ expiresIn: '1h' }
);
res.status(200).json({
token: token
});
})
.catch(err => {
return res.status(401).json({
msg: err
});
});
});
router.post("/profile", (req, res, next) => {
})
module.exports = router;
events.js
var express = require('express');
var router = express.Router();
const Event = require('../models/event');
const checkAuth = require('../middleware/check-auth');
router.post("/createEvent", checkAuth, (req, res, next) => {
const event = new Event({
title: req.body.title,
description: req.body.description,
date: req.body.date,
time: req.body.time,
location: req.body.location,
invite: req.body.invite,
private: req.body.private
});
event.save()
.then(result => {
res.status(201).json({
msg: "Event Created",
rslt: result
});
})
.catch(err => {
res.status(500).json({
err: err
});
});
});
module.exports = router;
Any suggestions on what I am doing wrong. It's a project that I started a couple of months ago and of course, didn't finish it. I just recently came back to it and can't seem to figure out why my server won't work. Seems to connect fine with the database.
As I can see, your typing '/' url, but in your code there is no '/' route.
Can you add the 'home' route as following, and check again please ?
app.use('/dashboard', eventsRouter);
app.use('/user', usersRouter);
// catch 404 and forward to error handler
// app.use(function(req, res, next) {
// next(createError(404));
// });
app.get('/', (req, res) => {
res.send('home');
});
// 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');
});
#RickyMed have you defined any middleware for / route. Generally 404 Not Found came when url is not present. If not create one or try http://localhost:3000/user.
Check if this is working

CORS error when serving angular with express

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));

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

babel-node, cannot get server to listen on port

I am currently trying to run node es6 with babel on a docker container and am running into some issues getting the app to start listening on port 3000. I can see where the app.js file is being processed as I am seeing the database connection code running. The problem seems to be even though app.js is getting called I am not seeing anything from /bin/www getting called which would result in the server listening on port 3000.
This is the command that is getting called to start the container:
nodemon ./bin/www -L --exec babel-node --inspect=0.0.0.0:56745
app.js:
……
(async () => {
try {
console.log('about to start the database connection... - 1');
mongoose.set('useCreateIndex', true);
mongoose.Promise = global.Promise;
console.log('about to start the database connection... - 2');
setTimeout(async () => {
await mongoose.connect(process.env.DB_HOST, {useNewUrlParser: true});
}, 60000);
//await mongoose.connect(process.env.DB_HOST, {useNewUrlParser: true});
console.log('about to start the database connection... - 3');
let db = mongoose.connection;
console.log('about to start the database connection... - 4');
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
console.log('about to start the database connection... - 5');
} catch (e) {
console.log('We have an error.....');
console.log(e);
}
})()
let app = express();
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')));
app.use(helmet());
app.use(methodOverride());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/group', groupsRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use((err, req, res, next) => {
if (process.env.NODE_ENV === "development") {
app.use((err, req, res, next) => {
if (err instanceof NotFoundError) {
//res.status(404).send(err.message);
res.statusCode = 404;
return res.json({
errors: [err.stack]
});
} else {
//res.status(500).send('An error occurred while processing your request.');
res.statusCode = 500;
return res.json({
errors: [err.stack]
//errors: ['An error occurred while processing your request.']
});
}
});
}
// production error handler
// no stacktraces leaked to user
console.log('about to begin configurations..... 7');
if (process.env.NODE_ENV !== "development") {
app.use((err, req, res, next) => {
if (err instanceof NotFoundError) {
//res.status(404).send(err.message);
res.statusCode = 404;
return res.json({
errors: [err.stack]
});
} else {
//res.status(500).send('An error occurred while processing your request.');
res.statusCode = 500;
return res.json({
errors: [err.stack]
//errors: ['An error occurred while processing your request.']
});
}
});
}
});
module.exports = app;
/bin/www:
#!/usr/bin/env node
/**
* Module dependencies.
*/
let app = require('../app');
let debug = require('debug’)(‘myapp:server');
let http = require('http');
/**
* Get port from environment and store in Express.
*/
let port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
let server = http.createServer(app);
/**
* 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.
*/
const normalizePort = (val) => {
debug('port = ' + val);
let 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.
*/
const onError = (error) => {
debug('Houston we have a problem');
if (error.syscall !== 'listen') {
throw error;
}
let 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.
*/
const onListening = () => {
debug('Listening');
let addr = server.address();
let bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
.babelrc:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread", "transform-async-to-generator"]
}
Update:
The issue seems to be with node and the arrow operator. When I changed to the function keyword, it started working. I added the following to my .bablerc file:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread", "transform-async-to-generator", "transform-es2015-arrow-functions"]
}
but it is still an issue. How can I use the arrow operator with nodejs?
If you aren't able to progress past the normalizePort call, are you sure it exists at that time?
You need to move the definition of the function above the place you use it.
(If you are used to old, pre-ES6 "function hoisting" using vars and functions, you should note that that does not work with const and let statements.)

Resources