在javascript / angularjs中获取客户端IP

编程入门 行业动态 更新时间:2024-10-15 16:25:32
本文介绍了在javascript / angularjs中获取客户端IP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

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

但是它

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

Error: XMLHttpRequest cannot load l2.io/ip.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '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:

freegeoip

测试以下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/json/?callback=", true); xhttp.send();

或者在jQuery的情况下使用:

Or in case of jQuery Use:

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

更多推荐

在javascript / angularjs中获取客户端IP

本文发布于:2023-11-25 23:42:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631814.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   javascript   angularjs   IP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!