我忘记了我问过这个问题, ANSWER 是here
我正在尝试使用AngularJS控制器来显示Nodejs的IP地址,我似乎无法正确获得控制器的$ http部分......我做错了什么?
var requestIp = require('request-ip');
// to convert the ip into geolocation coords
var geoip2 = require('geoip2');
var express = require('express');
var app = express();
var port = process.env.PORT || 8000;
// set view engine
app.set('view engine', 'ejs');
// public folder
app.use(express.static(__dirname + '/public'));
geoip2.init(); // init the db
// you can override which attirbute the ip will be set on by
// passing in an options object with an attributeName
app.use(requestIp.mw({ attributeName : 'myCustomAttributeName' }));
// respond to one req
app.get('/', function (req, res, next) {
// http://sahatyalkabov.com/jsrecipes/#!/backend/get-users-location-from-ip-address
//res.send('Your IP Address: ' + req.ip);
//next();
var ip = req.myCustomAttributeName;// use this for live
//var ip = '207.97.227.239';/* use this for testing */
console.log('requestIP is ' + ip);
//res.end('Hi, your IP address is ' + ip + '\n');
//res.render('index');
next();
// geolocation
geoip2.lookupSimple(ip, function(error, result) {
if (error) {
console.log("Error: %s", error);
}
else if (result) {
console.log(result);
}
});
res.render('index');
});
//custom
app.listen(port, function(){
console.log('user location app is running');
});
这就是我的Nodejs应用程序。它使用2个Node mods,request-ip和geoip2来请求IP地址,然后为它查找地理定位数据。
这是我的AngularJS代码
angular.module('UserLocation', []);
angular.module('UserLocation')
.controller('MainController', MainController);
MainController.$inject = ['$http'];
/*function ctrlFunc () {
this.message = 'Hello World again';
};*/
function MainController($http) {
var vm = this;
vm.result = {
city: null
};
vm.message = 'Hello World';
vm.message1 = 'Hello World again';
// user location
//function getLocation () {
vm.getLocation = function() {
return $http.get('localhost:8000', {
//return coreService.getLocation(city, {
params: {city: city}
})
.then(function(result){
var city = result.city;
return vm.result.city = result.map(function(item) {
return item.city.result;
})
});
};
};
这是一个地理定位数据的console.log,我试图在浏览器中显示(目前只是城市)
{ country: 'US',
continent: 'NA',
postal: '78218',
city: 'San Antonio',
location:
{ accuracy_radius: 1000,
latitude: 29.4889,
longitude: -98.3987,
metro_code: 641,
time_zone: 'America/Chicago' },
subdivision: 'TX' }
我在哪里遇到Angular的$ http中的GET
请求?如果这是我出错的地方......仍然是Node的新手,所以我不确定......
更新1 这是我通过EJS
提供的HTML文件 <html ng-app="UserLocation">
<title>The MEAN Stack</title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
</head>
<body ng-controller="MainController as vm">
{{ vm.message }}
<br>
{{ vm.message1 }}
<br>
{{ vm.result.city }}
<script src="/assets/js/app.js"></script>
</body>
</html>