[英]How to get country code and Country name using IP in react js
我正在开发一个基于 react.js 的应用程序。 应用程序中的一项要求是检测打开它的位置(国家/地区),然后使用该国家/地区的国旗预先填写表格上的电话号码字段。
我认为通过首先检测 IP 地址然后使用此 IP 地址找出国家名称会更有效地完成。 为此,我尝试了许多库,例如“iplocation”、“geoip-country-lite”、“ip”等,但这些库与我的应用程序不兼容。 任何人都可以建议我使用其他图书馆可以获得国家名称吗?
或者有任何其他有效的解决方案而不是检测 IP 地址,例如从浏览器获取一些可以获取国家名称的信息? 请指导。
您可以在不使用 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>
)
}
使用 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);
});
},[])
您可以使用外部 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.