Plesk Already in use NODEJS - node.js

I have this problem on my server using PLesk ,
Specs: Ubuntu 18.0.40.1 , Plesk
I tried to change the port to random numbers and the same results, says already in use.I would like to do the deploys well to be able to learn, I can try elsewhere but it is a priority to do it in plesk
Nodejs Config:
const app = express();
//CORS
const domainWhiteList = [process.env.ORIGIN1,process.env.ORIGIN2]
app.use(cors({
origin: function (origin, callback) {
console.log(origin)
if (!origin || domainWhiteList.includes(origin)) {
return callback(null,origin)
}
return callback('Not allowed by CORS ' + origin)
}
}));
//Uso de cookies
app.use(cookieParser());
//Activar JSON Body Leer
app.use(express.json());
//Api de Inicio de Sesion
app.use("/api/v1/auth", authRouter);
//Api Links
app.use("/api/v1/links", linkRouter)
//Port Default
const PORT = process.env.PORT || 5000;
//App se ejecuta en este port
app.listen(PORT, () => {console.log("Server is running on port:"+ PORT + " http://localhost:"+ PORT)});
Error: listen EADDRINUSE: address already in use :::4657
at Server.setupListenHandle [as _listen2] (node:net:1740:16)
at listenInCluster (node:net:1788:12)
at Server.listen (node:net:1876:7)
at Function.listen (/var/www/vhosts/vexshe.fun/proyects.vexshe.fun/node_modules/express/lib/application.js:635:24)
at file:///var/www/vhosts/vexshe.fun/proyects.vexshe.fun/index.js:47:5
at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1767:8)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'EADDRINUSE',
errno: -98,
syscall: 'listen',
address: '::',
port: 4657
}
Node.js v19.6.0```
I try to deploy my proyect in plesk , i do it in render and works fine but in plesk doesnt work.

Related

Trying to set up Node.js application under subdomain on Windows Server

I'm attempting to set up my first Node.js application on Windows Server. The application runs fine with the command:
node index.js
It'll run my application on localhost:8000. However, I want it to run on a subdomain on port 80, so I tried the following command:
set PORT=80 && set HOST=api.mydomain.com && node index.js
And here is my index.js file, which handles setting the PORT and HOST in the app.listen command:
import express from 'express';
import bodyParser from 'body-parser';
const expressJwt = require('express-jwt');
const config = require('./environment.json')[process.env.NODE_ENV || 'development'];
const app = express();
const port = +process.env.PORT || 8000;
const host = process.env.HOST || 'localhost';
// Skipping app.use commands...
app.get('/', root);
app.listen(port, host, 34, err => {
if (err) return console.error(err);
return console.log(`Server is listening on ${port}`);
});
Unfortunately, using a subdomain errors:
events.js:187
throw er; // Unhandled 'error' event
^
Error: getaddrinfo ENOTFOUND api.mydomain.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:26) Emitted 'error' event on Server instance at:
at GetAddrInfoReqWrap.doListen [as callback] (net.js:1485:12)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:60:17) { errno: 'ENOTFOUND', code: 'ENOTFOUND', syscall: 'getaddrinfo',
hostname: 'api.mydomain.com ' }
What is the proper way to configure the Node.js application to run under the subdomain? If I were using IIS it'd be as simple as adding additional Bindings, but now I'm in Node.js land instead so have no idea how to go about it.
host
No for your application to run locally with this domain name you must modify the host configurations to make api.mydomaine.com correspond to the ip address 127.0.0.1 on your machine
I ended up just running it under IIS, using a reverse proxy. Then I could use IIS to set up the subdomain binding, much simpler...
https://dev.to/petereysermans/hosting-a-node-js-application-on-windows-with-iis-as-reverse-proxy-397b

Heroku Nodejs application crashed after started

My nodejs app is crashing in Heroku. I have two server running in two different ports. One for express routes and another for socket.io. Apps builds fine and deployed in Heroku. It starts, DB connection is OK, then a server daemon also works fine for some period. Then it change state to crashed. No error log after the crash and no reason for crash. Here is log from Heroku,
2020-04-22T14:52:19.980682+00:00 app[web.1]: > iLearn#1.0.0 start /app
2020-04-22T14:52:19.980683+00:00 app[web.1]: > PORT=5000 node server.js
2020-04-22T14:52:19.980683+00:00 app[web.1]:
2020-04-22T14:52:20.741515+00:00 app[web.1]:
2020-04-22T14:52:20.782048+00:00 app[web.1]: API server started on: 5000
2020-04-22T14:52:21.087402+00:00 app[web.1]: Messaging Manager started..
2020-04-22T14:52:21.087501+00:00 app[web.1]: MessagingManager::startDaemon
2020-04-22T14:52:21.089358+00:00 app[web.1]: Messaging server running on port:5001
2020-04-22T14:52:21.130079+00:00 app[web.1]: DB Connected
2020-04-22T14:52:21.132905+00:00 app[web.1]: {"timestamp":"2020-04-22T14:52:21.131Z","message":"DB Connected","level":"info"}
2020-04-22T14:52:26.097164+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:31.100561+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:36.107406+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:41.112479+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:46.116481+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:51.121785+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:52:56.127394+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:53:01.136499+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:53:06.136680+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:53:11.144029+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:53:16.145616+00:00 app[web.1]: MessagingManager::daemon
2020-04-22T14:53:16.792389+00:00 heroku[web.1]: State changed from starting to crashed
Here is my server.js file,
const express = require('express')
const MessagingManager = require("./util/messagingManager")
app = express()
bodyParser = require('body-parser');
require('dotenv').config();
port = process.env.PORT || 5000;
app.listen(port);
console.log('API server started on: ' + port);
app.use(express.static('public'))
//app.use(formidable());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.set('view engine', 'pug');
app.set('views', './views')
var routes = require('./routes'); //importing route
app.use('/', routes); //register the route
const messagingApp = express();
const messagingServer = require("http").createServer(messagingApp);
const io = require("socket.io").listen(messagingServer);
let messagingManager = new MessagingManager()
messagingManager.startDaemon()
port = process.env.MESSAGING_PORT || 5001;
io.on("connection", socket => {
console.log("a user connected");
let id = socket.handshake.query.id
console.log(socket.id)
messagingManager.addConnection(id, socket)
socket.on("message", msg => {
if (msg.type == "MESSAGE_READ_STATUS")
messagingManager.setMessageStatus(msg)
else
messagingManager.sendMessage(msg)
});
socket.on("disconnect", () => {
//io.emit("chat message", msg);
});
socket.on("endsession", msg => {
//io.emit("chat message", msg);
console.log("session ended." + id)
messagingManager.removeConnection(msg.id)
socket.disconnect()
});
// not used
socket.on("session", msg => {
//io.emit("chat message", msg);
console.log("session established")
messagingManager.addConnection(msg.id, socket)
});
});
messagingServer.listen(port, () => console.log("Messaging server running on port:" + port));
It's hard to actually to know why the application crashed as log just says, application crashed without any message. Port binding error was not thrown and app listen callback function is called. Actual issue seems to be port. I have set port in both .env and package.json file. It overrides heroku dynamic port. Thanks #Beppe C to pointing out this. I deleted port variable from both .env and package.json and redeploy the app. Now it is working fine. Another issue is heroku app does not allow two port in the same application. So, I have to create two app. One for express HTTP route and another for socket.io. Hope it helps someone.

Connection Error with MongoDB and Express

Trying to connect my express app with mongodb atlas, but I keep getting this MongodbNetworkError
Server.js file
const express = require("express")
const mongoose = require("mongoose")
const dotenv = require("dotenv")
dotenv.config()
const app = express()
mongoose
.connect(process.env.MONGODB_KEY, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("MongoDB connected"))
.catch(err => console.error(err))
const PORT = process.env.PORT || 5000
app.listen(PORT, () => console.log(`Server running on port ${PORT}`))
Command Line
[nodemon] starting `node server.js`
Server running on port 5000
{ Error: getaddrinfo ENOTFOUND coolcluster-shard-00-00-wqaqv.mongodb.net coolcluster-shard-00-00-
wqaqv.mongodb.net:27017
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
name: 'MongoNetworkError',
errorLabels: [ 'TransientTransactionError' ],
[Symbol(mongoErrorContextSymbol)]: {} }
You need to whitelist the IP address of your nodejs server in MongoDB.
After login to the account, Follow the steps
Go to IP Whitelist view.
a)In the Security section of the left navigation, click Network Access. The IP Whitelist tab displays.
b)Click plus icon Add IP Address.
https://docs.atlas.mongodb.com/security-whitelist/#add-whitelist-entries

Couldn't resolve the error coming for mongodb atlas after deploying it on heroku?

In locally the application works perfectly but when i deployed it on heroku it showing errors on heroku logs. Also data wasn't added in mongoDb database. Actually in the application i used google-oauth login so in locally it works perfectly but not in heroku. I've also whitelisted my ip on mongodb atlas but still can't figure out why this error getting.
Anybody help me plz.....
Here is my prod.js file
module.exports = {
googleClientID: process.env.GOOGLE_CLIENT_ID,
googleClientSecret: process.env.GOOGLE_CLIENT_SECRET,
mongoURI: process.env.MONGO_URI,
cookieKey: process.env.COOKIE_KEY
}
Here is my keys.js file
// Keys.js - figure out what credentials should return
if (process.env.NODE_ENV === "production") {
// So we are in prodution - return the prod set of keys
module.exports = require('./prod');
} else {
// We are developement - return the dev keys
module.exports = require('./dev');
}
Here is my index.js file
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const cookieSession = require('cookie-session');
const keys = require('./config/keys');
require('./models/User');
require('./services/passport');
const app = express();
//Middleware
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey]
})
);
app.use(passport.initialize());
app.use(passport.session());
// mongoDb Connection
mongoose.connect(keys.mongoURI, {
useNewUrlParser: true
}).then(() => console.log('MongoDb Connect successfully'))
.catch(err => console.log(err));
// actual routes
require('./routes/authRoutes')(app);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server is running in ${PORT}`));
Actually i getting two different errors first was this
2019-09-02T06:28:59.760121+00:00 app[web.1]: Warning: connect.session() MemoryStore is not
2019-09-02T06:28:59.760149+00:00 app[web.1]: designed for a production environment, as it will leak
2019-09-02T06:28:59.760151+00:00 app[web.1]: memory, and will not scale past a single process.
2019-09-02T06:28:59.763577+00:00 app[web.1]:
2019-09-02T06:28:59.763581+00:00 app[web.1]: /app/node_modules/mongoose/lib/connection.js:519
2019-09-02T06:28:59.763583+00:00 app[web.1]: throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
2019-09-02T06:28:59.763585+00:00 app[web.1]: ^
2019-09-02T06:28:59.763838+00:00 app[web.1]: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
2019-09-02T06:28:59.763842+00:00 app[web.1]: at new MongooseError (/app/node_modules/mongoose/lib/error/mongooseError.js:10:11)
2019-09-02T06:28:59.763844+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:519:11)
2019-09-02T06:28:59.763846+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:321:15)
2019-09-02T06:28:59.763848+00:00 app[web.1]: at Object.<anonymous> (/app/index.js:24:10)
2019-09-02T06:28:59.763850+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:701:30)
2019-09-02T06:28:59.763852+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
2019-09-02T06:28:59.763854+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:600:32)
And the second one is this
2019-09-02T08:49:22.115492+00:00 app[web.1]: { MongoNetworkError: failed to connect to server [productionproj-shard-00-00-qfouv.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to productionproj-shard-00-00-qfouv.mongodb.net:27017 closed]
So on...... as same as above
Here is my mongodb production url i've been added on heroku config vars
mongodb+srv://nansProdDeploy:nansProdDeploy#productionproj-qfouv.mongodb.net/test?retryWrites=true&w=majority
It's all about whitelisting the correct ip address. When we put our application on heroku we must whitelist the ip by clicking [ Allow Access From Anywhere ] button and then click ok your ip will be 0.0.0.0/0 this ip will allow to access your deployed heroku application. When you are using your application locally at that point of you have to choose [ Add Current Ip Address ] to access your application locally

TypeError: server.connection is not a function in Hapi nodejs

I started working with Hapi nodejs framework. I am using "hapi#17.2.0" and here is my code in server.js to initiate application.
'use strict';
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 3000, host: 'localhost' });
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});
After running my project with node server.js from terminal it's throwing error as given below.
/var/www/html/hello_hapi/server.js:6
server.connection({ port: 3000, host: 'localhost' });
^
TypeError: server.connection is not a function
at Object.<anonymous> (/var/www/html/hello_hapi/server.js:6:8)
at Module._compile (module.js:612:30)
at Object.Module._extensions..js (module.js:623:10)
at Module.load (module.js:531:32)
at tryModuleLoad (module.js:494:12)
at Function.Module._load (module.js:486:3)
at Function.Module.runMain (module.js:653:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I found a solution to resolve my error. I just replaced
server.connection({ port: 3000, host: 'localhost' });
with
const server = new Hapi.Server({ port: 3000, host: 'localhost' });
Here is the description below:
According to hapi v17.0.0 they Removed support for multiple connections for a single server
The server.connection() method is replaced with options passed directly when creating a server object.
connection property is removed from all objects.
All connection methods moved to the server.
Removed support for labels and select() methods and options.
In hapi 16, there was support for server.connection(), but in hapi 17, they replaced server.connection() and instead
const Hapi = require('hapi')
const server = Hapi.server({
port:3000 || process.env.port
})
This can be used in node js.
If you are using typescript and typings, then
const server = new Hapi.server({port:3000 || process.env.port})
replace with this
const server = new Hapi.Server({
host: 'localhost',
port: 3000
})
if you are using this
server.connection({
port: 8000,
host: 'localhost'
});

Resources