When I am trying to run the application, then the Server Listining & Database Connected Successfully but App is crashed directly.
Could not get any response at http://localhost:4000/
Here is the full error, nodemon version is 3.1.0
[nodemon] starting `node server.js`
Server Listining on port: 4000
Database Connected Successfully
node:events:492
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::4000
at Server.setupListenHandle [as _listen2] (node:net:1872:16)
at listenInCluster (node:net:1920:12)
at Server.listen (node:net:2008:7)
at Function.listen (D:server\node_modules\express\lib\application.js:635:24)
at D:\server\server.js:25:13
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1899:8)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'EADDRINUSE',
errno: -4091,
syscall: 'listen',
address: '::',
port: 4000
}
Node.js v20.9.0
[nodemon] app crashed - waiting for file changes before starting...
server.js full source code
const express = require('express');
const app = express();
const connectDB = require('./db/db');
app.get('/', (req, res) => {
const obj = {
name: 'jam',
email: '[email protected]'
}
res.json(obj);
})
PORT = 4000;
app.listen(PORT, () => {
console.log(`Server Listining on port: ${PORT}`)
})
connectDB(`mongodb://localhost:27017/attendance-db`)
.then(() => {
console.log('Database Connected Successfully');
app.listen(PORT, () => {
console.log(`Database Listining on port: ${PORT}`)
})
})
.catch((e) => console.log(e))
package.json
{
"name": "elb",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"dev": "nodemon server.js"
},
"keywords": [],
"author": "elb",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.19.2",
"mongoose": "^8.3.5",
"morgan": "^1.10.0"
},
"devDependencies": {
"nodemon": "^3.1.0"
}
}
I changed the PORT several time but result is the same
Thank you for your time
Error: listen EADDRINUSE: address already in use :::4000
It clearly means that you have already connected the PORT
to 4000
and you are again trying to connect the same PORT
.
You just need to remove a section of code from server.js
that you have defined after PORT = 4000;
just remove it from server.js
.The issue will be resolved.
app.listen(PORT, () => {
console.log(`Server Listining on port: ${PORT}`)
})
Remove only the mentioned code not the PORT
where you assigned 4000
just before the above mentioned code.Try this.