【问题标题】:How to get country code and Country name using IP in react js如何在反应js中使用IP获取国家代码和国家名称
【发布时间】:2019-06-23 11:26:36
【问题描述】:

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

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

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

【问题讨论】:

  • 兄弟,我需要同样的解决方案来解决同样的问题。

标签: javascript node.js reactjs


【解决方案1】:

您可以在不使用 jQuery 的情况下做到这一点。

从 npm 安装和导入 axios

import axios from 'axios'

用国家名称和国家代码初始化你的组件状态

constructor(props) {
    super(props);
    this.state = {
        countryName: '',
        countryCode: ''
    }
}

将此函数添加到您的组件中

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

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

调用它
componentDidMount(){
    this.getGeoInfo();
}

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

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

【讨论】:

    【解决方案2】:

    使用 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);
      });
    },[])
    

    【讨论】:

      【解决方案3】:

      您可以使用外部 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);
          });
      }
      <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>

      【讨论】:

      • 这些是付费服务。我已经遇到了很多。我不想使用这样的服务。有没有其他办法?
      • 嗯,也可以使用 HTML5 地理定位服务,但是用户必须获得批准才能提供他们的位置。如果您能找到完全免费的 IP 查找服务,那么 API 方法仍然有效!另外,ipapi.co 会允许一定数量的免费请求(我觉得是一个月30000),如果你不需要很大的数量,它会很好地工作。
      • 另外,也许看看hostip.info/use.html,看起来他们是免费服务。
      猜你喜欢
      • 2017-01-05
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 2016-11-27
      • 1970-01-01
      相关资源
      最近更新 更多