Using ExpressJS and AngularJS



我正在学习NodeJS和Express。我正在使用 Node 和 Express 以及 2 个 Node 模块来获取客户端的 IP 地址。这部分工作正常。我在尝试使用 AngularJS (1.x( 使用 Angular 在浏览器中显示来自节点模块的地理位置数据时遇到问题。我做错了什么,因为我无法在浏览器中通过 Angular 显示地理数据。

 // get IP address
app.get('/ip', 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);
    // geolocation
    geoip2.lookupSimple(ip, function(error, result) {
    if (error) {
        return res.status(400).json({error: 'Something happened'});
        }
        else if (result) {
        return res.send(result);
      }
    });
});

我相信我已快速正确提供静态文件

app.use('/assets', express.static(__dirname + '/public'));

还有索引.html在我的/public文件夹中,它提供AngularJS和我的Angular应用程序

    <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">
    <h1 style="color:blue;">{{ vm.message }}</h1>
    <br>
    <h2 style="color:red;">{{ vm.location }}</h2>
    <script src="/assets/js/app.js"></script>
</body>
</html>

和 Angular 应用程序

    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.location = '';
    vm.message = 'Hello World';
    // user location
    //function getLocation () {
    vm.getLocation = function() {
        $http({
            method: 'GET',
            url: 'localhost:8000/ip'
        }).then(function (result) {
            console.log(result);
            return vm.location = result;
        });
      }; 
    };

IP工作并显示在'/ip',但在'/'我得到Cannot GET /我对要在"/"处显示的地理数据做错了什么

让客户端应用程序处理路由

// All other routes should redirect to the index.html
app.route('/*')
  .get((req, res) => {
    res.sendFile(path.resolve(__dirname + '/public/index.html'));
});

最新更新