如何在react js中使用IP获取国家代码和国家名称

Muh*_*zan 10 javascript node.js reactjs

我正在开发一个基于 react.js 的应用程序。应用程序中的一项要求是检测打开它的位置(国家/地区),然后使用该国家/地区的国旗预先填写表格上的电话号码字段。

我认为通过首先检测 IP 地址然后使用此 IP 地址找出国家名称会更有效地完成。为此,我尝试了许多库,例如“iplocation”、“geoip-country-lite”、“ip”等,但这些库与我的应用程序不兼容。任何人都可以建议我使用其他图书馆可以获得国家名称吗?

或者有任何其他有效的解决方案而不是检测 IP 地址,例如从浏览器获取一些可以获取国家名称的信息?请指导。

小智 28

您可以在不使用 jQuery 的情况下执行此操作。

从 npm 安装和导入 axios

import axios from 'axios'
Run Code Online (Sandbox Code Playgroud)

使用国家/地区名称和国家/地区代码初始化您的组件状态

constructor(props) {
    super(props);
    this.state = {
        countryName: '',
        countryCode: ''
    }
}
Run Code Online (Sandbox Code Playgroud)

将此功能添加到您的组件中

getGeoInfo = () => {
    axios.get('https://ipapi.co/json/').then((response) => {
        let data = response.data;
        this.setState({
            countryName: data.country_name,
            countryCode: data.country_calling_code
        });
    }).catch((error) => {
        console.log(error);
    });
};
Run Code Online (Sandbox Code Playgroud)

并调用 this.getGeoInfo() 将国家名称和国家代码设置为您所在的州。我从componentDidMount()调用了它

componentDidMount(){
    this.getGeoInfo();
}
Run Code Online (Sandbox Code Playgroud)

您可以阅读状态以获取国家/地区名称和国家/地区代码

render() {
    return (
        <div>
            <p>Country Name: {this.state.countryName}</p>
            <p>Country Code: {this.state.countryCode}</p>
        </div>
    )
}
Run Code Online (Sandbox Code Playgroud)

  • 那么“法律视角”呢?我们是否需要询问用户是否可以获得他的位置? (3认同)

Jyo*_*han 7

使用 React 钩子,这可以像下面那样完成:

import React, { useEffect } from 'react';

 useEffect(() => {
   fetch('https://extreme-ip-lookup.com/json/')
   .then( res => res.json())
   .then(response => {
    console.log("Country is : ", response);
  })
  .catch((data, status) => {
    console.log('Request failed:', data);
  });
},[])
Run Code Online (Sandbox Code Playgroud)


Ter*_*nox 5

您可以使用外部 API 从客户端 IP 地址获取位置详细信息。

我已经重做这个以使用http://api.hostip.info,它可以免费使用,并且我使用 Fetch 而不是 jQuery 来提取数据。

function getElementText(response, elementName) {
    return response.getElementsByTagName(elementName)[0].innerHTML;
}

function getIpAddress() {

    fetch('http://api.hostip.info').then(response => {
         return response.text();
    }).then(xml => { 
        return (new window.DOMParser()).parseFromString(xml, "text/xml");
    }).then(xmlDoc => {
         countryName = getElementText(xmlDoc , "countryName");
         countryCode = getElementText(xmlDoc , "countryAbbrev");
         $("#output").html("Country name: " + countryName + "<br>" + "Country code: " + countryCode);
    });
}
Run Code Online (Sandbox Code Playgroud)
<div style="text-align:center;line-height:30px;">

<button onclick="getIpAddress()">Click me to get IP AddressInfo </button>
  
  <div id="output">Location:</div>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
Run Code Online (Sandbox Code Playgroud)