js_原生js獲取當前的使用者ip

Syinho發表於2024-05-08
  • 透過向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)

相關文章