1

I have tried using the following approach but when hosted the application . I'm getting the ip address that the application us hosted on. Also I have used req.ip and req.socket.remoteAddress but it was returning the local host ip I.e ,::1

here is what I tried.

var express = require('express');
var request = require('request');
var app = express();
const IPData = require("ipdata").default;
require('dotenv').config();

const apiKey = process.env.API_KEY;
const ipdata = new IPData(apiKey);

app.get('/location', async (req, res) => {
    try{
        request.get('http://ipinfo.io/ip', (error, response, body) => {
            if (!error && response.statusCode == 200) {
                let clientIp = req.headers["x-forward-ip"] || body
                console.log(body);
                ipdata.lookup(clientIp)
                    .then((data) => {
                        console.log(data);
                        return res.json({
                            city: data.city,
                            region: data.region,
                            country: data.country_name,
                            postal: data.postal
                        });
                    })
                    .catch((error) => {
                        console.log(error);
                        res.status(500).send('Error looking up location');
                    });
            }
        });

    }catch(error) {
        console.log(error);
        res.status(500).send('Error looking up location');
    }
   
});

app.listen(8000, () => {
    console.log('Server started on port 8000');
});
  • 1
    Does this answer your question? [How to determine a user's IP address in node](https://stackoverflow.com/questions/8107856/how-to-determine-a-users-ip-address-in-node) – eol Jan 27 '23 at 10:14

1 Answers1

0

Try this:

const express = require("express");
const app = express();
const IpGeoLocation = require("ip-geolocation-api-javascript-sdk");
app.get("/", (req, res) => {
  // Get client's IP address
  const clientIp = req.connection.remoteAddress;
  // Initialize IpGeoLocation with your API key
  const apiKey = "YOUR_API_KEY";
  const ipGeoLocation = new IpGeoLocation(apiKey);
  // Get location information for the client's IP address
  ipGeoLocation
    .getGeoLocation(clientIp)
    .then((location) => {
      console.log(location);
      res.send(location);
    })
    .catch((error) => {
      console.error(error);
      res.status(500).send(error);
    });
});
app.listen(3000, () => {
  console.log("Server listening on port 3000");
});
const ipGeoLocation = require("ip-geolocation-node");
const clientIp = req.connection.remoteAddress;
ipGeoLocation
  .getGeoLocation(clientIp)
  .then((location) => {
    console.log(location);
  })
  .catch((error) => {
    console.error(error);
  });
Tyler2P
  • 2,324
  • 26
  • 22
  • 31