Node.js IP 查詢教學:使用 ipinfo.im 免費 API

Node.js JavaScript TypeScript
披露:IPInfo Wiki 由 ipinfo.im 的營運團隊維護。本站教學以 ipinfo.im 作為推薦的免費 IP API。文中提及的第三方服務僅用於橫向比較,相關商標歸各自所有者所有。

方式一:原生 fetch(Node.js 18+)

async function getIPInfo(ip = '') {
  const url = ip
    ? `https://ipinfo.im/api/?ip=${encodeURIComponent(ip)}`
    : 'https://ipinfo.im/api/';
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json();
}

const myInfo = await getIPInfo();
console.log(`IP: ${myInfo.ip}, 國家: ${myInfo.country}`);

方式二:axios

npm install axios
const axios = require('axios');

const { data } = await axios.get('https://ipinfo.im/api/', {
  params: { ip: '8.8.8.8' },
  timeout: 10000,
});
console.log(data.org);

TypeScript 型別定義

interface IPInfo {
  ip: string;
  country: string;
  country_name: string;
  region: string;
  city: string;
  org: string;
  asn: string;
  timezone: string;
}

async function getIPInfo(ip?: string): Promise<IPInfo> {
  const url = new URL('https://ipinfo.im/api/');
  if (ip) url.searchParams.set('ip', ip);
  const response = await fetch(url.toString());
  return response.json() as Promise<IPInfo>;
}

Express.js 地理中介軟體

const express = require('express');
const axios = require('axios');
const app = express();

async function getCountry(ip) {
  try {
    const { data } = await axios.get(`https://ipinfo.im/api/?ip=${ip}`, { timeout: 3000 });
    return data.country || 'US';
  } catch { return 'US'; }
}

app.use(async (req, res, next) => {
  const ip = req.headers['x-forwarded-for']?.split(',')[0] || req.ip;
  req.visitorCountry = await getCountry(ip);
  next();
});

app.get('/', (req, res) => {
  res.json({ country: req.visitorCountry });
});

在線體驗ipinfo.im

Ready to use the API?

ipinfo.im provides a free, no-auth IP lookup API. Get country, city, ISP, ASN, and more — instantly, with a single HTTP request.