我正在学习 Nodejs 和 ExpressJS。我正在尝试使用 ExpressJS 和 2 个 Node 模块(request-ip 和 geoip2)来获取用于地理定位的客户端 IP 地址,然后使用 AngularJS (1.x) 在浏览器中输出地理定位。
到目前为止,我的 Nodejs 和 Expressjs 代码是
var express = require('express');
// require request-ip and register it as middleware
var requestIp = require('request-ip');
// to convert the ip into geolocation coords
var geoip2 = require('geoip2');
// Init app
var app = express();
var port = process.env.PORT || 8000;
geoip2.init(); // init the db
//app.use(requestIp.mw({ attributeName: 'myCustomAttributeName'}));
var ip = '207.97.227.239';//67.183.57.64, 207.97.227.239
// respond to homepage req
app.get('/', function (req, res, next) {
//var ip = req.myCustomAttributeName;// use this for live
//var ip = '207.97.227.239';/* use this for testing */
console.log('requestIP is ' + ip);
next();
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error) {
console.log("Error: %s", error);
}
else if (result) {
console.log(result);//ipType was causing console.log duplication, IDK why
}
});
});
// set static folder
app.use('/', express.static(__dirname + '/public'));
app.listen(port, function(){
console.log('user location app is running');
});
对于 Angular,我有
angular.module('UserLocation', []);
angular.module('UserLocation')
.controller('MainController', MainController);
MainController.$inject = ['$http'];
function MainController($http) {
var vm = this;
vm.result = '';
vm.message = 'Hello World';
vm.getLocation = function() {
console.log();
return $http.get('localhost:8000', {
params: {result: result}
})
.then(function(result){
console.log(result);
})
};
};
Angular Controller 中的 vm.result
用于执行地理定位的 geoip2 Node 模块的结果。
我可以在控制台中获取结果
,没问题,但我不确定如何将它传递给 Angular。我正在使用 $http
服务,但我不确定从这里到哪里...?
如何使用 $http 将 result
从 geoip2 Node 模块传递到我的 Angular Controller ?
最佳答案
问题是你在完成之前调用 next。
app.get('/', function (req, res, next) {
//next(); this line should be commented
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error)
return res.status(400).json({error: 'Something happened'});
return res.send(result);
});
});
然后在 Angular 上
$http({
method: 'GET',
url: '/yourURL'
}).then(function (response) {
console.log(response);
});
如果要使用用户IP获取位置:
app.get('/', function (req, res, next) {
//next(); this line should be commented
// geolocation
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
req.connection.socket.remoteAddress;
geoip2.lookupSimple(ip, function(error, result) {
if (error)
return res.status(400).json({error: 'Something happened'});
return res.send(result);
});
});
关于angularjs - 使用Nodejs、Express和AngularJS在浏览器中显示IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41944036/