如何使用Geoip在NodeJ上获取当前城市名称

时间:2017-12-04 11:22:44

标签: javascript node.js geoip

我想应用Geoip在Nodejs上获取当前城市的名称,然后我尝试通过Npm安装Geoip包,但是在Windows上运行时似乎有些错误,所以我该怎么办才能解决问题

4 个答案:

答案 0 :(得分:1)

尝试使用IP2Location Node.js

https://github.com/ip2location-nodejs/IP2Location

预备知识

http://lite.ip2location.com/下载免费的LITE数据库,并在下面使用。

安装

npm install ip2location-nodejs

用法

var ip2loc = require("ip2location-nodejs");

ip2loc.IP2Location_init("/path_to_your_database_file/your_BIN_file.BIN");

testip = ['8.8.8.8', '2404:6800:4001:c01::67', '2001:0200:0102:0000:0000:0000:0000:0000', '2001:0200:0135:0000:0000:0000:0000:0000', '2001:0200:017A:0000:0000:0000:0000:0000'];
for (var x = 0; x < testip.length; x++) {
    result = ip2loc.IP2Location_get_all(testip[x]);
    for (var key in result) {
        console.log(key + ": " + result[key]);
    }
}

答案 1 :(得分:1)

要从IP获取国家或城市,请尝试此操作。

var geoip = require('geoip-lite');
  

https://github.com/bluesmoon/node-geoip

$ npm install geoip-lite

var ip = "207.97.227.239";
var geo = geoip.lookup(ip);

console.log(geo);
{ range: [ 3479297920, 3479301339 ],
  country: 'US',
  region: 'TX',
  city: 'San Antonio',
  ll: [ 29.4889, -98.3987 ],
  metro: 641,
  zip: 78218 }

答案 2 :(得分:0)

我刚刚为我创建的IPLocate.io API发布了一个NPM模块。

超级简单,无需下载数据库,每天免费请求1,500个。

安装

npm install node-iplocate

用法

const iplocate = require("node-iplocate");

iplocate("8.8.8.8").then(function(results) {
  console.log("IP Address: " + results.ip);
  // IP Address: 8.8.8.8
  console.log("Country: " + results.country + " (" + results.country_code + ")"); 
  // Country: United States (US)
  console.log("Continent: " + results.continent); 
  // Continent: North America
  console.log("Organisation: " + results.org + " (" + results.asn + ")"); 
  // Organisation: Google LLC (AS15169)

  console.log(JSON.stringify(results, null, 2));
  /*
    {
      "ip": "8.8.8.8",
      "country": "United States",
      "country_code": "US",
      "city": null,
      "continent": "North America",
      "latitude": 37.751,
      "longitude": -97.822,
      "time_zone": null,
      "postal_code": null,
      "org": "Google LLC",
      "asn": "AS15169"
    }
  */
});

// Or with callbacks
iplocate("8.8.8.8", null, function(err, results) {
  // ...
  console.log(JSON.stringify(results, null, 2));
});

// Provide an API key from IPLocate.io
iplocate("8.8.8.8", { api_key: "abcdef" }).then(function(results) {
  // ...
});

答案 3 :(得分:0)

如果有人正在寻找免费的内存解决方案: https://www.npmjs.com/package/@avindak/xgeoip

const geoip = require('@avindak/xgeoip');

await geoip.load_memory();
//AU
let res = await geoip.resolve("1.1.1.1");
console.log(res.country_code);