방법 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