前端获取ip和IP地址信息

文章讲述了如何使用Axios库从国外域名获取IP地址,包括通过`axios.post`和`script`标签实现跨域请求的方法,以及处理返回数据的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下述方法经检验是能获取到信息的,但是查询域名是国外的,待考虑。

axios.post("https://pv.sohu.com/cityjson?ie=utf-8");
    axios
        .get("https://api.ipify.org?format=json")
        .then((response) => {
            const ipAddress = response.data.ip;
            axios
                .get(`https://ipapi.co/${ipAddress}/json/`)
                .then((response) => {
                   this.location = `${response.data.city}, ${response.data.region}, ${response.data.country}`;
                })
                .catch((error) => {
                    console.log(error);
                });
        })
        .catch((error) => {
            console.log(error);
        });

下述代码是搜狐获取ip信息,通过创建script标签,设置src为"https://pv.sohu.com/cityjson?ie=utf-8",来获取IP信息,然后处理返回的数据。

    function handleResponse(data) {
        console.log(data); // 处理从跨域接口返回的数据
    }

    var script = document.createElement("script");
    script.src = "https://pv.sohu.com/cityjson?ie=utf-8"; // 将回调函数名作为URL参数传递
    document.body.appendChild(script);
    script.onload = function (da) {
        // 在这里可以处理脚本加载完成后的逻辑
        handleResponse(returnCitySN);
    };
    ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值