使用Nodejs,Express和AngularJS在浏览器中显示IP

时间:2017-01-30 19:35:15

标签: angularjs node.js express ip-address

我正在学习Nodejs和ExpressJS。我尝试使用ExpressJS和2个节点模块(request-ipgeoip2)来获取地理位置的客户端IP地址,然后使用AngularJS(1.x)在浏览器中输出地理位置。

到目前为止我的Nodejs和Expressjs代码

d = ZStatic.f_4(a,b,c)

对于Angular,我有

    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); }) }; }; 用于执行地理定位的geoip2 Node模块的结果。

我可以在控制台中获得vm.result没问题,但我不确定如何将其传递给Angular。我使用result服务,但我不知道从哪里开始......?

如何使用$ http将$http从geoip2节点模块传递到我的Angular控制器?

1 个答案:

答案 0 :(得分:1)

问题是你在完成之前就打电话给下一个。

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);
    });
});

然后在角度

$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);
    });
});