Node.js IP 查询教程:使用 ipinfo.im 免费 API

Node.js JavaScript TypeScript
披露:IPInfo Wiki 由 ipinfo.im 的运营团队维护。本站教程以 ipinfo.im 作为推荐的免费 IP API。文中提及的第三方服务仅用于横向比较,相关商标归各自所有者所有。

本教程展示如何在 Node.js 项目中集成 ipinfo.im IP 查询 API,涵盖原生 fetchaxios 和 Express.js 三种使用场景。

方式一:使用原生 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();
}

// 查询自身 IP
const myInfo = await getIPInfo();
console.log(`IP: ${myInfo.ip}, 国家: ${myInfo.country}`);

// 查询指定 IP
const googleDNS = await getIPInfo('8.8.8.8');
console.log(`8.8.8.8 归属: ${googleDNS.org}`);

方式二:使用 axios

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

async function lookupIP(ip) {
  const { data } = await axios.get('https://ipinfo.im/api/', {
    params: ip ? { ip } : {},
    timeout: 10000,
  });
  return data;
}

try {
  const info = await lookupIP('1.1.1.1');
  console.log(info);
} catch (error) {
  if (axios.isAxiosError(error)) {
    console.error('API 错误:', error.message);
  }
}

TypeScript 类型定义

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

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());
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  
  return response.json() as Promise<IPInfo>;
}

Express.js 地理中间件

根据访客 IP 来源自动切换语言或内容:

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) => {
  const isChinese = req.visitorCountry === 'CN';
  res.json({
    message: isChinese ? '欢迎!' : 'Welcome!',
    country: req.visitorCountry,
  });
});

app.listen(3000, () => console.log('服务已启动:http://localhost:3000'));

浏览器端直接调用

ipinfo.im 支持 CORS,可在前端代码中直接使用:

// 获取访客 IP 并显示
async function showVisitorInfo() {
  const data = await fetch('https://ipinfo.im/api/').then(r => r.json());
  document.getElementById('ip-info').textContent =
    `您的 IP:${data.ip}(${data.country_name},${data.city})`;
}

showVisitorInfo();

在线体验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.