我正在学习 Nodejs 和 ExpressJS。我正在尝试使用 ExpressJS 和 2 个节点模块(请求IP https://www.npmjs.com/package/request-ip and geoip2 https://www.npmjs.com/package/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);
})
};
};
vm.result
Angular 控制器中的 是用于执行地理定位的 geoip2 Node 模块的结果。
我可以得到result
在控制台中没问题,但我不确定如何将其传递给 Angular。我正在使用$http
服务,但我不知道从这里去哪里......?
我该如何通过result
使用 $http 从 geoip2 Node 模块到我的 Angular 控制器?