Search code examples
node.jserror-handlingdnsportpermission-denied

can not run my nodejs project on every port


i write following code in config.js for connect to mongodb

const mongoose=require('mongoose');
 const PORT=3000;
const connectionString=`mongodb://localhost:3000:sale`;


mongoose.connect(connectionString,(err)=>{
    (err)? console.log('Fail to connect to mongodb'):console.log('Connect success.');
});

module.exports=mongoose;

and create model in model.js:

const { default: mongoose } = require("mongoose");
const { stringify } = require("nodemon/lib/utils");


const _product=mongoose.Schema({
    id:{
        type:Number,
        require:true
    },
    name:{
        type:String,
        require:true
    },
    description:{
        type:String,
        require:false
    }
});


module.exports=mongoose.model('product',_product);

and in app.js write following code:

const express = require("express");
const app=express();
// require('dotenv').config();
require('./Database/config.js');
const product=require('./model/model.js');
 const PORT=3000;

app.listen(PORT,'Run on port '+ PORT);

app.post('/insert',async(req,res)=>{
const newProduct=new product({
    name:'GLX SHAHIN 3',
    id:1,
    description:'Newest iranian phone'
});
try{
    await newProduct.save();
    res.send(`Inserted : ${newProduct}`);
}
catch(err){
    res.send(err);
}
});

when i run npx nodemon app.js or node app.js get ENOTEFOUND error sometime EACCES error:

Fail to connect to mongodb
node:events:498
      throw er; // Unhandled 'error' event   
      ^

Error: getaddrinfo ENOTFOUND Run on port 3000
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26)
Emitted 'error' event on Server instance at:
    at GetAddrInfoReqWrap.doListen [as callback] (node:net:1513:12)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:17) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'Run on port 3000'

note that i get these error on every port not only on specific port.


Solution

  • Try this in App.js

    const express = require("express");
    const app=express();
    
    // require('dotenv').config();
    require('./Database/config.js');
    const product=require('./model/model.js');
     const PORT=3000;
    
    
    
    app.post('/insert',async(req,res)=>{
    const newProduct=new product({
        name:'GLX SHAHIN 3',
        id:1,
        description:'Newest iranian phone'
    });
    try{
        await newProduct.save();
        res.send(`Inserted : ${newProduct}`);
    }
    catch(err){
        res.send(err);
    }
    });
    
    app.listen(PORT, () => 'Run on port '+ PORT);