Cris Cris - 4 days ago 5
AngularJS Question

Angular send User IP in a post request

How can i get the user IP and send it in a post request?

.controller('LinkCtrl', function($scope, $http){

$http.get("http://ipinfo.io").then(function(response){
$scope.userIp = response.data
})

$scope.onClickLink = function($event){
$http.post('http://localhost:7000/api/message',
{
ip: userIp.ip
})
}
})


My attempt sais : ReferenceError: userIp is not defined

Answer

You forgot $scope before the variable name, you added an Ip in the scpe variable and used it without scope. so the error.

.controller('LinkCtrl', function($scope, $http){

    $http.get("http://ipinfo.io").then(function(response){
        $scope.userIp = response.data
    })

    $scope.onClickLink = function($event){
        $http.post('http://localhost:7000/api/message', 
            {
                ip: $scope.userIp.ip
            })
    }    
})
Comments