js_原生js获取当前的用户ip

  • 通过向https://api.ipify.org/发起请求来获取用户ip
// utils/index.js
export const getUserIp1 = async function () {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        if ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304) {
          resolve(xhr.responseText)
        } else {
          reject('failed ajax')
        }
      }else{
        reject('failed connect')
      }
    }
    xhr.open('get', 'https://api.ipify.org/', true)
    xhr.send(null)
  })
}

export const getUserIp2 = async function () {
  const requestOptions = {
    method: 'GET',
    redirect: 'follow',
  }

  return fetch('https://api.ipify.org/', requestOptions)
    .then(response => response.text())
    .then(result => result)
    .catch(() => 'failed fetch')
}
// page.html
import { getUserIp1, getUserIp2 } from '@/utils/index.js'
const ip = await getUserIp1().catch(err => err)
console.log(ip)
const ip2 = await getUserIp2().catch(err => err)
console.log(ip2)
posted @ 2024-05-08 01:21  Syinho  阅读(51)  评论(0编辑  收藏  举报