an error while connecting node js with mongoDB - node.js

In the Backend folder, I created a server.js file.
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
//connect with mongoDB
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
//import routes
//const exercisesRouter = require('./routes/exercises');
//const usersRouter = require('./routes/users');
//use routes
//app.use('/exercises', exercisesRouter);
//app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
after I entered nodemon server command.
Here What printed in the terminel
[nodemon] 2.0.20
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): .
[nodemon] watching extensions: js,mjs,json
[nodemon] starting node server.js
(node:92140) [MONGOOSE] DeprecationWarning: Mongoose: the strictQuery option will be switched back to false by default in Mongoose 7. Use mongoose.set('strictQuery', false); if you want to prepare for this change. Or use mongoose.set('strictQuery', true); to suppress this warning.
(Use node --trace-deprecation ... to show where the warning was created)
node:events:491
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::5000
at Server.setupListenHandle [as _listen2] (node:net:1733:16)
at listenInCluster (node:net:1781:12)
at Server.listen (node:net:1869:7)
at Function.listen (/Users/masterlwa/Desktop/exercise-tracker/backend/node_modules/express/lib/application.js:635:24)
at Object. (/Users/masterlwa/Desktop/exercise-tracker/backend/server.js:32:5)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Module._load (node:internal/modules/cjs/loader:922:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1760:8)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 5000
}
Node.js v18.13.0
[nodemon] app crashed - waiting for file changes before starting...
Currently, I do not have an idea regarding how to fix this. How to fix this?

seems like port 5000 is alreay in used by another app, try to change port to 5001 or something else

Related

How to run my app.js on random ports for running the node js we application

I am facing a trouble some problem where, I need kill everytime a given port to run my app.js which is front end for node js and
here is my app.js
var express = require("express");
var path = require("path");
//var routes = require("./routes");
var app = express();
app.set("port", process.env.PORT || 3000);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
app.use("/public",express.static(path.resolve(__dirname,"public")));
app.use("/", require("./routes/web"));
app.use("/api", require("./routes/api"));
app.listen(app.get("port"), function(){
console.log("Server started on port " + app.get("port"));
})
> coedataapp#1.0.0 build
> node app
node:events:505
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (node:net:1372:16)
at listenInCluster (node:net:1420:12)
at Server.listen (node:net:1508:7)
at Function.listen (/Users/xxxxxx/Documents/my-learning/coe-central/node_modules/express/lib/application.js:635:24)
at Object.<anonymous> (/Users/xxxxx/Documents/my-learning/coe-central/app.js:17:5)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1399:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 3000
}
Added my app.js code as well as the error I see in the console log. This will save my time and I will be able to make this serverless in future.

nodemon app crashed - waiting for file changes before starting ... Error

appjs
const express = require("express");
const path = require("path");
const homeRouter = require("./routes/home.routes");
const app = express();
const port = 8000;
app.use(express.static(path.join(__dirname, "assets")));
app.use(express.static(path.join(__dirname, "images")));
app.set("view engine", "ejs");
app.set("views", "views");
app.use("/", homeRouter);
app.listen(port, () => {
console.log(`server listen on port ${port}`);
});
home routes
const router = require('express').Router()
const homeController = require('../controllers/home.controller')
router.get('/', homeController.getHome)
module.exports = router
homecontroller
const productsModel = require('../models/products.models')
exports.getHome = (req,res,next) => {
//get products
//get render index.ejs
productsModel.getAllproducts().then(products => {
res.render('index', {
products: products
})
})
}
products.models
const mongoose = require("mongoose");
const DB_URL = 'mongodb://localhost:27017/shop'
const productsSchema = mongoose.Schema({
name:String,
image:String,
price:String,
category:String,
description:String
})
const product = mongoose.model('product', productsSchema)
exports.getAllproducts = () => {
//connect to db
//get products
//disconnect
return new Promise((resolve,reject) => {
mongoose.connect(DB_URL).then(() => {
return product.find({})
}).then(products => {
mongoose.disconnect()
resolve(products)
}).catch(err => reject(err))
})
}
Error
node:events:504
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::8000
at Server.setupListenHandle [as _listen2] (node:net:1330:16)
at listenInCluster (node:net:1378:12)
at Server.listen (node:net:1465:7)
at Function.listen (C:\Users\islam\OneDrive\Desktop\shopnode\node_modules\express\lib\application.js:635:24)
at Object. (C:\Users\islam\OneDrive\Desktop\shopnode\app.js:17:5)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) Emitted 'error' event on Server
instance at:
at emitErrorNT (node:net:1357:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) { code: 'EADDRINUSE',
errno: -4091, syscall: 'listen', address: '::', port: 8000 }
[nodemon] app crashed - waiting for file changes before starting...
In case we have some project running are both same port and on your server then catch this error and i have solve in that time.
open terminal set your Dir location and run this command on your terminal
doing this things
using this command :- pkill node
or
for mac :- sudo killall -9 node
or
for windows :- > killall -9 node
or
killall node
otherwise use this on your defined port modify your code
var port = process.env.PORT || 8000;
do all this things then server restart
npm start or node app.js

I'm not able to start the mongo db server, getting the following error: [nodemon] app crashed - waiting for file changes before starting

This is server.js and .env file
I'm trying to start the server but it is throwing an error.
server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true });
const connection = mongoose.connection;
connection.once('open',() => {
console.log("MongoDB database connection established successfully");
})
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
})
.env
ATLAS_URI = mongodb+srv://rnvsri:vastav123#cluster0.dgnw1.mongodb.net/test?retryWrites=true&w=majority
Issue:
In cmd, I'm giving the command nodemon server.js
but the server is not starting and it is throwing the following error.
nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
node:events:368
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::5000
at Server.setupListenHandle [as _listen2] (node:net:1334:16)
at listenInCluster (node:net:1382:12)
at Server.listen (node:net:1469:7)
at Function.listen (/Users/rnvsrivastava/mern/restaurant-reviews/backend/backend/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/Users/rnvsrivastava/mern/restaurant-reviews/backend/backend/server.js:20:6)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1361:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 5000
}
[nodemon] app crashed - waiting for file changes before starting...
Can someone help?
port you are using is used by another process you can find it by
command
lsof -i :PORT and can kill using kill command
kill PID

Got an error listen EADDRINUSE: address already in use :::5000 while restarting a server

So, I have a simple express server which connects to the mongoDB atlas by mongoose.
And for example I starting the server, everything works fine but when I do restart(no matter with nodemon or just by using node) I got an error:
Error: listen EADDRINUSE: address already in use :::5000
at Server.setupListenHandle [as _listen2] (net.js:1313:16)
at listenInCluster (net.js:1361:12)
at Server.listen (net.js:1447:7)
at Function.listen (C:\Users\Олег\e-commerce-mern\MERN-shop-app\node_modules\express\lib\application.js:618:24)
at Object.<anonymous> (C:\Users\Олег\e-commerce-mern\MERN-shop-app\backend\server.js:36:20)
at Module._compile (internal/modules/cjs/loader.js:1138:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)
at Module.load (internal/modules/cjs/loader.js:986:32)
at Function.Module._load (internal/modules/cjs/loader.js:879:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1340:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: '::',
port: 5000
}
and after restarting one or few times my server starts working just fine without the error, but then, after saving again the problem repeats and i don't know why.
db.js:
const mongoose = require('mongoose');
const mongoConnection = () => {
return mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
});
};
module.exports = mongoConnection;
server.js:
const express = require('express');
const products = require('./data/products'); //my mock data
const dotenv = require('dotenv');
// eslint-disable-next-line no-unused-vars
const colors = require('colors');
const dbConnect = require('./config/db');
dotenv.config();
dbConnect()
.then(() => {
// callback();
console.log('db connected');
})
.catch((err) => {
console.error(`Error: ${error.message}`.red.underline.bold);
process.exit(1);
});
const app = express();
app.get('/', (req, res) => {
res.send('app is running');
});
app.get('/api/products', (req, res) => {
res.json(products);
});
app.get('/api/products/:id', (req, res) => {
const product = products.find((p) => p._id === req.params.id);
res.json(product);
});
const PORT = process.env.port || 5000;
const server = app.listen(PORT,
// eslint-disable-next-line max-len
console.log(`server running in ${process.env.NODE_ENV} on port ${PORT}`.yellow.bold));
process.on('unhandledRejection', (err) => {
console.log('err', err.name, err.message);
console.log('unhadled rejection');
server.close(() => {
process.exit(1);
});
});
As you see, nothing too fancy here, yes, I understand that my port isn't killed on restart but I don't understand that behaviour and how to prevent it.
P.S. I'm using windows.
This error raised because any application running on port 5000.
To fix it you just need to kill the running application on port 5000.
Follow the steps below:
Step 0: stop your application If you are currently trying to run it on port 5000
Step 1: run command prompt as administrator
Step 2: run
-->" netstat -ano | findstr :5000 " <--
command to find the running application's pid number.
Note: In my case it is 4208
Step 4: run taskkill /PID {pid number} /F to kill the running process.
Now you can run your app on port 5000
Update : Got a shortcut to kill the process
Just run TASKKILL /IM node.exe /F
Then start your application :-)

Error in running server via node and express

i am still new in backend but i am facing an error since yesterday whenever i try to run my server. BELOW IS MY CODE AND ERROR
const express = require("express");
const app = express();
PORT = 8443;
app.listen("PORT", () => {
console.log("Server up and running")
});
AND HERE IS MY ERROR
events.js:288
throw er; // Unhandled 'error' event
^
Error: listen EACCES: permission denied PORT
←[90m at Server.setupListenHandle [as _listen2] (net.js:1292:21)←[39m
←[90m at listenInCluster (net.js:1357:12)←[39m
←[90m at Server.listen (net.js:1456:5)←[39m
at Function.listen (C:\Users\AbTorres9\Desktop\YelpCamp\node_modules\←[4mexpress←[24m\lib\application.js:618:24)
at Object.<anonymous> (C:\Users\AbTorres9\Desktop\YelpCamp\app.js:6:5)
←[90m at Module._compile (internal/modules/cjs/loader.js:1158:30)←[39m
←[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)←[39m
←[90m at Module.load (internal/modules/cjs/loader.js:1002:32)←[39m
←[90m at Function.Module._load (internal/modules/cjs/loader.js:901:14)←[39m
←[90m at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)←[39m
Emitted 'error' event on Server instance at:
←[90m at emitErrorNT (net.js:1336:8)←[39m
←[90m at processTicksAndRejections (internal/process/task_queues.js:84:21)←[39m {
code: ←[32m'EACCES'←[39m,
errno: ←[32m'EACCES'←[39m,
syscall: ←[32m'listen'←[39m,
address: ←[32m'PORT'←[39m,
port: ←[33m-1←[39m
}
[nodemon] app crashed - waiting for file changes before starting...
const express = require("express");
const app = express();
const PORT = 8443;
app.listen(PORT, () => {
console.log("Server up and running")
});
you had some errors first of all you did not initialized the PORT and second you passed PORT as string in app.listen()
You are missing a view normal JavaScript things. Like defining port. And the .listen function takes in the port variable rather than a string saying "PORT"
See working example:
const express = require('express');
const app = express();
const port = 8443;
app.listen(port, () => console.log(`Server running on port ${port}!`));
#Abhishek, I think on which port are you using that is block by your environment kindly allow it on the firewall or just disable the firewall and access again it works for you!!
You should use the variable and not the string in the app.listen() function. Try to use something like this:
app.listen(PORT, () => {
console.log("Server up and running")
});

Resources