使用ExpressJS和AngularJS

我正在学习NodeJS和Express。 我使用Node和Express以及2个Node模块来获取客户端的IP地址。 那部分工作正常。 我在尝试使用AngularJS(1.x)在浏览器中使用Angular从Node模块显示地理位置数据时遇到了问题。 我做错了什么,因为我不能在浏览器中通过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')); 

而我的/公共文件夹中的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> 

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