having issue connecting my mongodb to my nodejs app - node.js

//in my .env file
MOVIEREVIEWS_DB_URI=mongodb+srv://driiisdev:password123#cluster1.ektx7.mongodb.net/sample_mflix?retryWrites=true&w=majority
PORT=8000 //starting port of server
//in my index.js file
import app from "./server.js"
import mongodb from "mongodb"
import dotenv from "dotenv"
dotenv.config();
const uri = process.env.MOVIEREVIEWS_DB_URI;
const client = new mongodb.MongoClient(uri);
const port = process.env.PORT||5000;
(async ()=>{
try{
//Connect to the MongoDB cluster
await client.connect();
app.listen(port, ()=>{
console.log("server is running on port:" +port);
})
}catch(e){
console.error(e);
process.exit(1)
}
})().catch(console.error);
//in my server.js file
import express from 'express'
import cors from 'cors'
import movies from './api/movies.route.js'
const app = express()
app.use(cors())
app.use(express.json())
app.use("/api/v1/movies", movies)
app.use('*', (req,res)=>{
res.status(404).json({error:"not found"})
})
export default app
// on running nodemon server , the error i get:
Error: listen EACCES: permission denied 8000 //starting port of server
at Server.setupListenHandle [as _listen2] (node:net:1317:21)
at listenInCluster (node:net:1382:12)
at Server.listen (node:net:1480:5)
at Function.listen (C:\xampp\htdocs\driiisdev\movie-reviews\backend\node_modules\express\lib\application.js:635:24)
at main (file:///C:/xampp/htdocs/driiisdev/movie-reviews/backend/index.js:19:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1361:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EACCES',
errno: -4092,
syscall: 'listen',
address: '8000 //starting port of server',
port: -1
}

Related

an error while connecting node js with mongoDB

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

How to connect a remote server from client by http.get of Node.js?

I'm using node.js to create connect to server on EC2.
The client.js is on the physical machine using a function http.get to get to the server.js on EC2, which using the express.get to connect.
When I ran the two file on the EC2 and my physical machine, nothing happened. And I had the error of Error: connect ETIMEDOUT.
Am I using the wrong ip address? What I use is the public Ipv4 ip.
server.js on EC2 with Ipv4 add: 100.27.18.131
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
calc = 0
for (i=0;i<10000;i++) {
calc += Math.random() * Math.random();
}
console.log(calc);
res.send(calc.toFixed(10));
});
app.listen(port, () => {
console.log(`listening on port ${port}`);
});
client.js on pyhsical machine:
const http = require('http');
setInterval(loadtest, 100); //time is in ms
function loadtest()
{
http.get('http://100.27.18.131:3000', (res) => {
res.on('data', function (chunk) {
console.log('' + chunk);
});
});
}
Error:
node:events:505
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT 100.27.18.131:3000
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16)
Emitted 'error' event on ClientRequest instance at:
at Socket.socketErrorListener (node:_http_client:454:9)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -4039,
code: 'ETIMEDOUT',
syscall: 'connect',
address: '100.27.18.131',
port: 3000
}
Did not set up the port for 3000 or 80 at the vary beginning.

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

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

How to fix the error "connect ECONNREFUSED"?

C:\Users\fc\Desktop\js-basics\Projects>node net.js
Gives this error:
Error: connect ECONNREFUSED 127.0.0.1:8085
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1056:14) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8085
}
Two ways you can solve this issue.
1.You can kill port which is listening on 8085 sudo killall node
2.You can change the port number. Here's a working example:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!'); // This will serve your request to '/'.
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!');
});

Resources