前端获取ip和IP地址信息

222 阅读1分钟

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

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为"pv.sohu.com/cityjson?ie…",来获取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);
    };
    ```