是否可以使用NodeJS根据IP地址找到设备地理位置?

rqcrx0a6  于 2022-10-22  发布在  Go
关注(0)|答案(3)|浏览(409)

我正在尝试实现一个功能,比如Instagram提供的功能;我说的是它的“登录活动”页面。这就是我要说的:

用户每次登录时,当前正在使用的设备都存储在页面中。我该怎么做呢?
我的当前代码使用了两个库,一个用于从正在使用的设备查找ip.Address(),另一个用于帮助我获取有关给定IP地址的位置数据。遗憾的是,我无法让它发挥作用。代码如下所示:

const ipLocation = require('ip-to-location')
const ip = require('ip')

const loc = await ipLocation.fetch(ip.address())
console.dir('Location', loc)
await User.findOneAndUpdate(
  { email: req.body.email },
  {
    $push: {
      loginActivity: {
        type: 'Point',
        coordinates: [loc.longitude, loc.latitude],
        // formattedAddress: loc[0].formattedAddress,
        // street: loc[0].streetName,
        city: loc.city.city,
        state: loc.region_name,
        zipcode: loc.zip_code,
        country: loc.country_code,
      },
    },
  }
)

是否有其他库可供使用?或者,有没有人给我指个正确的方向,让这一切成为可能?

qoefvg9y

qoefvg9y1#

如果您可以获得用户的IP地址,您可以尝试ipgeolocation.io
这是一个免费的API,可以给你一个IP地址的纬度和经度值(如果你需要的话,还有更多)。
更多信息,请访问documentation

r6hnlfcb

r6hnlfcb2#

您可以尝试使用IP2Location Node.js。
https://github.com/ip2location/ip2location-nodejs
它可以调用数据库文件(freepaid),也可以调用web service
对于数据库,代码如下所示:

const {IP2Location} = require("ip2location-nodejs");

let ip2location = new IP2Location();

ip2location.open("./DB25.BIN");

testip = ['8.8.8.8', '2404:6800:4001:c01::67'];

for (var x = 0; x < testip.length; x++) {
    result = ip2location.getAll(testip[x]);
    for (var key in result) {
        console.log(key + ": " + result[key]);
    }
    console.log("--------------------------------------------------------------");
}

ip2location.close();

对于Web服务,您可以使用以下示例:

const {IP2LocationWebService} = require("ip2location-nodejs");

let ws = new IP2LocationWebService();

let ip = "8.8.8.8";
let apiKey = "YOUR_API_KEY";
let apiPackage = "WS25";
let useSSL = true;

// addon and lang to get more data and translation (leave both blank if you don't need them)
let addon = "continent,country,region,city,geotargeting,country_groupings,time_zone_info";
let lang = "fr";

ws.open(apiKey, apiPackage, useSSL);

ws.lookup(ip, addon, lang, (err, data) => {
    if (!err) {
        console.log(data);

        ws.getCredit((err, data) => {
            if (!err) {
                console.log(data);
            }
        });
    }
});
f4t66c6m

f4t66c6m3#

您可以尝试我们的服务,IPinfo API或Node.js library。仅在免费层上,您每月就会收到多达50,000个IP位置查找请求。
用户每次登录时,当前正在使用的设备都存储在页面中。我该怎么做呢?
对于设备位置,最准确的方法是要求用户通过Web应用程序的地理位置API(MDN Web Docs)提供他们的位置,但这需要用户同意提供该信息。但使用基于IP地址的地理定位,你不需要任何同意就可以获得准确到城市级别的大致位置。
IPinfo Node.js库非常容易使用。您可以在此处找到文档:https://github.com/ipinfo/node

第一步:安装库

在您的Node.js项目中安装库:

npm install node-ipinfo

第二步:使用库的基础知识

注册后,获得令牌并安装node-ipinfo模块。运行样板代码:

const { IPinfoWrapper } = require("node-ipinfo")

// After you have signed up, get your token from: ipinfo.io/account/token
const YOUR_TOKEN = ""

// initialize the ipinfo handler function
const ipinfo = new IPinfoWrapper(YOUR_TOKEN)

// I am using a fixed IP but you would need to pass your visitor/client's IP address here 
let ip_address = "8.8.8.8"

// printing out the entire response
ipinfo.lookupIp(ip_address).then((response) => {
    console.log(response)
})

运行此代码后,您将看到如下所示的输出:

{
  ip: '8.8.8.8',
  hostname: 'dns.google',
  anycast: true,
  city: 'Mountain View',
  region: 'California',
  country: 'United States',
  loc: '37.4056,-122.0775',
  org: 'AS15169 Google LLC',
  postal: '94043',
  timezone: 'America/Los_Angeles',
  countryCode: 'US'
}

此操作返回一个作为响应的javascript对象。

第三步:获取特定信息字段

根据您的代码,您也可以从response对象中提取特定的字段,但streetname除外。IP地址位置不提供街道地址级别的准确性,因此您必须选择HTML Geolocation API。但对于其余部分,您可以获得可靠的结果。

const { IPinfoWrapper } = require("node-ipinfo");

const YOUR_TOKEN = "";
const ipinfo = new IPinfoWrapper(YOUR_TOKEN)
let ip_address = "8.8.8.8"

ipinfo.lookupIp(ip_address).then((response) => {
    // console.log(response)
    console.log({
        coordinates: response.loc.split(","),
        city: response.city,
        state: response.region,
        zipcode: response.postal,
        country: response.country
    })

})

他们的回应是:

{
  coordinates: [ '37.4056', '-122.0775' ],
  city: 'Mountain View',
  state: 'California',
  zipcode: '94043',
  country: 'United States'
}

其他注意事项:如果你想知道如何从访问者那里获取IP地址,请查看StackOverflow帖子:
Node.js: Get client's IP
TLDR:使用req.ip

相关问题