Node.js和PHP根据ip获取地理位置的方法
时间:2023-11-14 21:23:13
一、Node.js实现代码
var http = require('http');
var util = require('util');
/**
* 根据 ip 获取获取地址信息
*/
var getIpInfo = function(ip, cb) {
var sina_server = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=';
var url = sina_server + ip;
http.get(url, function(res) {
var code = res.statusCode;
if (code == 200) {
res.on('data', function(data) {
try {
cb(null, JSON.parse(data));
} catch (err) {
cb(err);
}
});
} else {
cb({ code: code });
}
}).on('error', function(e) { cb(e); });
};
getIpInfo('220.181.111.85', function(err, msg) {
console.log('城市: ' + msg.city);
console.log('msg: ' + util.inspect(msg, true, 8));
})
请求结果:
城市: 徐州
{
"ret": 1,
"start": "49.68.0.0",
"end": "49.68.255.255",
"country": "中国",
"province": "江苏",
"city": "徐州",
"district": "",
"isp": "电信",
"type": "",
"desc": ""
}
二、PHP实现代码
<?
$ip = "220.181.111.85";
$url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=$ip";
$data = file_get_contents($url);
$result = json_decode($data);
echo "城市:" . $result->city . "<br>";
print_r($result);
?>
请求结果:
城市:徐州
stdClass Object
(
[ret] => 1
[start] => 49.68.0.0
[end] => 49.68.255.255
[country] => 中国
[province] => 江苏
[city] => 徐州
[district] =>
[isp] => 电信
[type] =>
[desc] =>
)
标签:Nodejs,PHP,获取地理位置
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Django密码存储策略分析
2022-03-10 04:16:33
python beautifulsoup4 模块详情
2021-12-30 07:50:03
![](https://img.aspxhome.com/file/2023/3/107593_0s.webp)
如何在Python中创建二叉树
2022-07-30 06:27:35
![](https://img.aspxhome.com/file/2023/5/120645_0s.png)
从零开始学习Node.js系列教程二:文本提交与显示方法
2024-05-08 09:35:30
![](https://img.aspxhome.com/file/2023/9/129469_0s.jpg)
使用django自带的user做外键的方法
2023-04-16 06:54:36
![](https://img.aspxhome.com/file/2023/8/130578_0s.png)
Tensorflow获取张量Tensor的具体维数实例
2021-12-24 20:25:10
Python魔术方法专题
2023-03-14 15:38:02
不通过数据源名DSN也能访问Access数据库吗?
2009-10-29 12:22:00
Pytorch十九种损失函数的使用详解
2021-07-19 22:23:07
![](https://img.aspxhome.com/file/2023/0/95130_0s.png)
解析SQL Server中SQL日期转换出错的原因
2024-01-15 16:34:17
![](https://img.aspxhome.com/file/2023/7/113557_0s.png)
详解MySQL性能优化(一)
2024-01-18 11:39:52
![](https://img.aspxhome.com/file/2023/4/75634_0s.jpg)
python小程序实现刷票功能详解
2022-08-23 06:17:22
vue.js使用watch监听路由变化的方法
2024-05-10 14:16:22
![](https://img.aspxhome.com/file/2023/9/126489_0s.gif)
python3 解决requests出错重试的问题
2021-02-05 10:26:27
![](https://img.aspxhome.com/file/2023/4/105794_0s.jpg)
Vue2.0利用 v-model 实现组件props双向绑定的优美解决方案
2024-05-02 17:09:28
高性能JavaScript模板引擎实现原理详解
2024-04-18 09:37:11
![](https://img.aspxhome.com/file/2023/9/136369_0s.png)
python 双循环遍历list 变量判断代码
2021-02-10 12:38:12
HTML与javascript中常用编码浅析
2008-12-23 12:20:00
ASP中的Debug类--VBScript
2008-10-24 09:38:00
微软建议的ASP性能优化28条守则(2)
2008-02-22 17:02:00