我正在尝试学习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;
});
};
};
显示"你好世界"消息,但不显示位置...?我也可以去本地主机: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 而位置没有显示,而我似乎已正确配置了所有内容......所以很明显我做错了什么,我看不到...?
-
您已将"vm.location"初始化为字符串,而实际上它是一个 JSON 对象。
vm.location = {};
-
您需要将请求中的 url 参数调整为:
url: '/ip'
-
从 Express.js 发回 JSON 时,应将响应行更改为:
return res.json(result);
在此之后,您是否在代码中的某个地方调用vm.getLocation()
?
您需要的数据在响应对象的result.data
下。
此外,为了在 html 中显示数据,您必须指定要从vm.location
对象(vm.location.country
、vm.location.city
等(显示的属性。
来自关于$http的角度文档:
响应对象具有以下属性:
数据 – {字符串|对象} – 使用转换函数转换的响应正文。
状态 – {数字} – 响应的 HTTP 状态代码。
headers – {function([headerName](} – Header getter function.
config – {对象} – 用于生成请求的配置对象。
状态文本 – {字符串} – 响应的 HTTP 状态文本。
这个 express js 和 angular 托管在同一个端口上吗?如果是这样,请更换您的
$http({
method: 'GET',
url: 'localhost:8000/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
跟
$http({
method: 'GET',
url: '/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
});
它可能被视为 CORS 调用,您可能已禁用它。您还可以指定要then
的第二个函数(查看下面的代码(并查看是否调用了错误回调。
$http({
method: 'GET',
url: '/ip'
}).then(function (result) {
console.log(result);
return vm.location = result;
}, function (error) {
console.log(error);
});