【问题标题】:How to retrieve client ip address and find location using node js如何使用节点js检索客户端IP地址并查找位置
【发布时间】:2023-01-30 16:31:52
【问题描述】:

我曾尝试使用以下方法,但在托管应用程序时。我正在获取我们托管的应用程序的 IP 地址。 我也用过请求.ipreq.socket.remoteAddress但它正在返回本地主机 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');
});

【问题讨论】:

标签: node.js express ip ip-address


【解决方案1】:
 /// 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)
    });

【讨论】:

    猜你喜欢
    • 2015-09-07
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多