【发布时间】:2017-06-29 03:41:43
【问题描述】:
我正在尝试学习 ExpressJS,但在从 Express 路由获取 IP 地址以通过 Angular 控制器显示在浏览器中时遇到问题。
我正在使用 2 个 Nodejs 模块(request-ip 和 geoip2)来获取 IP,然后查找该 IP 的地理位置数据。然后尝试使用 Angular 使用 Angular $http get 调用在浏览器中显示地理位置数据。
我的 IP 快速路由:
// get IP address
router.get('/ip', function (req, res, next) {
console.log('requestIP is ' + ip);
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error) {
//return res.status(400).json({error: 'Something happened'});//default
return res.sendStatus(400).json({error: 'Something happened'});
}
else if (result) {
return res.send(result);
}
});
});
还有我的 AngularJS 控制器代码:
function MainController($http) {
var vm = this;
vm.message = 'Hello World';
vm.location = '';
vm.getLocation = function() {
$http({
method: 'GET',
url: 'localhost:8000/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
};
};
Hello World 消息显示但不显示位置...?我也可以访问 localhost:8000/ip 并查看 JSON result。 result 也不会出现在 Chrome 的控制台中。结果是一个像这样的 json 对象:
{"country":"US","continent":"NA","postal":"98296","city":"Snohomish","location":{"accuracy_radius":20,"latitude":47.8519,"longitude":-122.0921,"metro_code":819,"time_zone":"America/Los_Angeles"},"subdivision":"WA"}
我不确定为什么 Hello Word 会显示,而当我似乎已正确配置所有内容时,位置却没有显示...所以显然我做错了我看不到的事情...?
【问题讨论】:
-
根据您的承诺,使用 catch 块来捕获任何错误,然后将对该函数的调用链接到另一个调用以捕获并执行 console.log 或其他任何操作,您可能会得到一个错误
标签: angularjs json node.js express