Sahal
Sahal

Reputation: 109

Get client IP in javascript/angularjs

I'm trying to get client IP in my angular app. I'm using this code:

$http.get("http://l2.io/ip.js").then(function(response) {       
    $scope.ip = response.data;  
});

But it make

Error: XMLHttpRequest cannot load http://l2.io/ip.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9001' is therefore not allowed access.

How to add headers?

Upvotes: 1

Views: 9384

Answers (1)

Shakti Phartiyal
Shakti Phartiyal

Reputation: 6254

There is a service provider that provides CORS headers (Access-Control-Allow-Origin: *) for javascript based requests:

https://freegeoip.com

Test the following XMLHTTP request for a sample:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        console.log(xhttp.responseText)
    }
};
xhttp.open("GET", "//freegeoip.net/json/?callback=", true);
xhttp.send();

Or in case of jQuery Use:

$.getJSON('//freegeoip.net/json/?callback=?', function(data) {
  console.log(data);
});

Upvotes: 1

Related Questions