我们如何在React中知道用户位置或Ip地址?

问题描述 投票:0回答:1

我想知道用户位置,我尝试了多个 api,但如果我不提供 IP 地址,它们都会给我错误的州和城市名称,就像这个 api -> https://ipapi.co/json 但是如果我将 IP 地址传递给上面的 API,那么我会得到正确的州和城市名称。

那么任何人都可以建议如何获取用户 IP 地址,以便我可以传入上面的 url,或者我如何获取用户地址,例如正确的州和城市。 [我正在运行一个反应项目]

谢谢你

javascript reactjs react-hooks ip-address
1个回答
0
投票

在 React 应用程序中,出于安全和隐私考虑,您通常不会从客户端代码直接访问用户的 IP 地址。但是,您可以使用浏览器 API 或第三方服务获取用户的位置。

获取用户位置:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      const { latitude, longitude } = position.coords;
      console.log(`Latitude: ${latitude}, Longitude: ${longitude}`);
    },
    (error) => {
      console.error('Error getting geolocation:', error);
    }
  );
} else {
  console.error('Geolocation is not supported by this browser.');
}

第三方IP地理定位服务:

fetch('https://api.ipgeolocation.io/ipgeo?apiKey=YOUR_API_KEY')
  .then(response => response.json())
  .then(data => {
    console.log('User location:', data);
  })
  .catch(error => {
    console.error('Error fetching user location:', error);
  });
© www.soinside.com 2019 - 2024. All rights reserved.