简体   繁体   English

使用 ExpressJS 和 AngularJS

[英]Using ExpressJS and AngularJS

I'm learning NodeJS and Express.我正在学习 NodeJS 和 Express。 I'm using Node and Express along with 2 Node modules to get the client's IP address.我使用 Node 和 Express 以及 2 个 Node 模块来获取客户端的 IP 地址。 That part is working fine.那部分工作正常。 I'm having trouble trying to use AngularJS (1.x) to display the geolocation data from the Node module in the browser using Angular.我在尝试使用 AngularJS (1.x) 在浏览器中使用 Angular 显示来自 Node 模块的地理定位数据时遇到问题。 I'm doing something wrong because I can't get the geo data to show via Angular in the browser.我做错了,因为我无法在浏览器中通过 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);
      }
    });
});

I believe I have Express serving my static files correctly我相信我已经正确地为我的静态文件提供了 Express

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

And the index.html in my /public folder that serves up AngularJS and my Angular app我的 /public 文件夹中的 index.html 提供了 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>

And the Angular app和 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;
        });
      }; 
    };

The IP works and is displayed at '/ip' but at '/' I get Cannot GET / What am I doing wrong to the geo data to display at '/' IP 工作并显示在'/ip'但在'/'我得到Cannot GET /我在地理数据上做错了什么以显示在“/”

To let your client side application handle the routing让您的客户端应用程序处理路由

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM