Node.js IP 조회 튜토리얼: ipinfo.im 무료 API 사용

Node.js JavaScript TypeScript
공개: IPInfo Wiki는 ipinfo.im 운영팀이 관리합니다. 본 사이트의 튜토리얼은 ipinfo.im을 추천 무료 IP API로 소개합니다. 언급된 서드파티 서비스는 비교 목적으로만 사용됩니다. 모든 상표는 해당 소유자에게 귀속됩니다.

방법 1: 네이티브 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}`);

방법 2: 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.country); // "US"

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) => {
  const isKorea = req.visitorCountry === 'KR';
  res.json({ message: isKorea ? '안녕하세요!' : 'Hello!' });
});

app.listen(3000);

지금 바로 → 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.