在javascript / angularjs中获取客户端IP [英] Get client IP in javascript/angularjs

查看:1405
本文介绍了在javascript / angularjs中获取客户端IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的角应用中获取客户端IP。
我正在使用此代码:

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

但是它


错误:XMLHttpRequest无法加载 http://l2.io/ip.js 。请求的资源上不存在Access-Control-Allow-Origin标头。因此,不允许访问 http:// localhost:9001

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.

如何添加标题?

推荐答案

有一个服务提供商为基于javascript的请求提供CORS标头(Access-Control-Allow-Origin:*):

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

https://freegeoip.com

测试以下XMLHTTP请求样本:

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

或者在jQuery的情况下使用:

Or in case of jQuery Use:

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

这篇关于在javascript / angularjs中获取客户端IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆