0

I'm just getting used to NodeJS and MongoDB so please go gentle! I'm trying to "console.log" the "network Interfaces" to find the IP address.

No matter what I do, I keep getting an error:

"TypeError: Cannot read property '1' of undefined "

I suspect that it's this code in line 11:

    const ip = networkInterfaces.Ethernet[1].address;

Here is what is in my app.js file:

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const path = require("path");
const cors = require("cors");
const os = require("os");

const networkInterfaces = os.networkInterfaces();
const ip = networkInterfaces.Ethernet[1].address;
require("dotenv/config");

//import routes
const productRoute = require("./routes/product");
const cartRoute = require("./routes/cart");
const orderRoute = require("./routes/order");
const favoriteRoute = require("./routes/favorite");
const authRoute = require("./routes/auth");
const notification = require("./middlewares/pushNotification");

//Connect to DB
const dbURI = process.env.DB_CONNECTION;
mongoose.connect(
dbURI,
  {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
  },
  () => {
app.listen(process.env.PORT, ip);
let dirPath = path.join(
  __dirname,
  "public/api/static/images/productPictures"
);
let dirPathUser = path.join(
  __dirname,
  "public/api/static/images/userprofile"
);
createDir(dirPath);
createDir(dirPathUser);
console.log("Connected to DB");
  }
);

function createDir(dirPath) {
  if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true }, (err) => {
  if (err) {
    console.error("createDir Error:", err);
  } else {
    console.log("Directory is made!");
  }
    });
  }
}

...

  • Have you tried `console.log(os.networkInterfaces())` first? – Dharmaraj Sep 02 '21 at 05:22
  • @Dharmaraj Seem to get somewhere with that and populated some data: on [nodemon] starting `node app.js` { lo: [ { address: '127.0.0.1', netmask: '255.0.0.0', family: 'IPv4', mac: '00:00:00:00:00:00', internal: true, cidr: '127.0.0.1/8' }, ... Ended however with: TypeError: Cannot read property 'undefined' of undefined at Object. /app.js:11:38) – Konnect Holdings LLC Sep 02 '21 at 05:35
  • Can you update your question with the output? – Dharmaraj Sep 02 '21 at 05:35
  • @Dharmaraj [Nodemon] app crashed and Ended with a new error: ' TypeError: Cannot read property 'undefined' of undefined at Object. /app.js:11:38) ' – Konnect Holdings LLC Sep 02 '21 at 05:45
  • 1
    My system does not have a `["Ethernet"]` interface. It has `["Ethernet 2"]` and `["Ethernet 3"]`. You can't just blindly access a property name and assume it exists. Iterate the properties that exist and then choose one of those present to look at further. – jfriend00 Sep 02 '21 at 05:58
  • In most cases you don't need to use ip. You just listen on localhost and use proxy like Nginx to pass incomming requests to your app. Alternatively use 0.0.0.0 to make it listen on all the interfaces. – Molda Sep 02 '21 at 06:02
  • @jfriend00 How can I share the code so you can have a test run on your end? – Konnect Holdings LLC Sep 02 '21 at 06:02
  • @Molda How would I apply that in the code? – Konnect Holdings LLC Sep 02 '21 at 06:06
  • Why are you trying to get the IP address? Which IP address are you trying to get? What are you trying to accomplish? – jfriend00 Sep 02 '21 at 06:11
  • @jfriend00 I have been working on having the backend API up and running for a Mobile App I am creating... The issue is linking the database to the API and I suspect that the error I am receiving is my only hindrance. – Konnect Holdings LLC Sep 02 '21 at 06:24
  • You did not answer the questions I asked at all. I asked three questions. Please answer all of them. Probably you don't need to get an IP address for whatever you're trying to do so the best solution would be to help you solve the problem a different way. But, you have no explained precisely why you want an IP address in the first place. Can't help you if you won't provide the info we ask for. – jfriend00 Sep 02 '21 at 06:26
  • I am trying to configure my local IP for the server. My local IP is http://127.0.0.1 which I have the MongoDB server running but they don't seem to connect in order to complete the API. I hope that was a better answer @jfriend00 . – Konnect Holdings LLC Sep 02 '21 at 06:31
  • In nearly all configurations, you can just use `localhost` or `127.0.0.1` to connect to the current system without knowing what the actual network IP address is. I still don't understand why you're trying to get the IP address. – jfriend00 Sep 02 '21 at 06:35
  • @KonnectHoldingsLLC so your real problem is that you can't connect to your db right? If so then try to log the error variable which is the first param you get in the mongoose.connect's callback. So add console.log(arguments) just above app.listen – Molda Sep 02 '21 at 07:36
  • @Molda Will give that a shot. Thanks – Konnect Holdings LLC Sep 02 '21 at 10:13
  • This has turned out to be an [XY problem](https://en.wikipedia.org/wiki/XY_problem) where you failed to describe the actual problem (connecting to the database with appropriate diagnostics for that) and instead asked about some solution that is probably not the right solution path (getting or setting server's IP address). Please always describe the real problem and then you are free to include other information about attempted solutions, but please don't ask only about roadblocks you ran into in your own solution without first describing the original problem. – jfriend00 Sep 02 '21 at 21:14

2 Answers2

0

this answer will help you with network interfaces

If you are trying to get the client IP then you can use

const RequestIp = require("@supercharge/request-ip");
const ip = RequestIp.getClientIp(req);

inside your API

or to get the current machine address you can use child process

Piyush Dubey
  • 276
  • 1
  • 13
  • The OP's code is trying to get the server's IP address so I don't think this answer has anything to do with what they're asking about. – jfriend00 Sep 02 '21 at 06:12
  • @Piyush Dubey Got this error: node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot find module 'supercharge/request-ip' Require stack: -app.js – Konnect Holdings LLC Sep 02 '21 at 06:13
  • I have included both the answer in case anyone wants it tho – Piyush Dubey Sep 02 '21 at 06:14
  • @KonnectHoldingsLLC It is an external library to get the IP from client request – Piyush Dubey Sep 02 '21 at 06:15
  • @PiyushDubey Kool Maybe this will give a better understanding. For more context, I have been working on having the backend API up and running for a Mobile App I am creating... The issue is linking the database to the API and I suspect that the error I am receiving is my only hindrance. – Konnect Holdings LLC Sep 02 '21 at 06:26
  • So you want your application running on the same IP as your machine, but by default, express will run on the same machine. If you want to access the API from your mobile app. try replacing the localhost with the IP of you machine – Piyush Dubey Sep 02 '21 at 06:54
0

I solved the issue by removing Ethernet[1].address with en0[1].

line 11 now reads:

const ip =  networkInterfaces.en0[1].address;

I added this to the end of my App.js files:

const port = process.env.PORT || '3000';
const address = process.env.ADDRESS || '127.0.0.1';

app.listen(port,address, () => console.log('Server running on http:// ' + address + ':' + port +'/'));