Reputation: 1900
I'm learning NodeJS and Express. I'm using Node and Express along with 2 Node modules to get the client's IP address. 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. I'm doing something wrong because I can't get the geo data to show via Angular in the browser.
// 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
app.use('/assets', express.static(__dirname + '/public'));
And the index.html in my /public folder that serves up AngularJS and my Angular app
<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.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 '/'
Upvotes: 1
Views: 1412
Reputation: 2330
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'));
});
Upvotes: 3