Get client IP in javascript/angularjs

孤街醉人 提交于 2019-12-24 06:45:31

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/42901167/get-client-ip-in-javascript-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!