📋 HTTP 헤더
📖 정의
HTTP 헤더는 클라이언트와 서버가 추가 정보를 주고받기 위한 메타데이터입니다. 요청과 응답에 대한 정보, 인증, 캐싱, 콘텐츠 타입 등을 정의합니다.
🎯 비유로 이해하기
우편 봉투
HTTP 메시지 = 편지
├─ 봉투 (헤더)
│ ├─ 보내는 사람 주소 (User-Agent)
│ ├─ 받는 사람 주소 (Host)
│ ├─ 우편 종류 (Content-Type)
│ ├─ 중요도 (Priority)
│ └─ 반송 주소 (Referer)
└─ 편지 내용 (바디)
봉투(헤더)를 먼저 보고:
- 누가 보냈는지 확인
- 어떤 종류의 편지인지 파악
- 어떻게 처리할지 결정
💡 헤더의 구조
헤더 형식:
Header-Name: value
예시:
Content-Type: application/json
Authorization: Bearer abc123
User-Agent: Mozilla/5.0
📬 요청 헤더 (Request Headers)
Host
요청하는 서버의 호스트명과 포트
GET /api/users HTTP/1.1
Host: example.com
// fetch는 자동으로 Host 헤더 설정
fetch('https://example.com/api/users');
특징:
- HTTP/1.1부터 필수
- 하나의 IP에 여러 도메인 호스팅 가능 (가상 호스트)
- 브라우저가 자동으로 설정
User-Agent
클라이언트 애플리케이션 정보
GET /api/users HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36
// Node.js에서 커스텀 User-Agent 설정
fetch('https://api.example.com/users', {
headers: {
'User-Agent': 'MyApp/1.0'
}
});
용도:
- 브라우저/OS 식별
- 통계 수집
- 호환성 처리
- 봇 탐지
Accept
클라이언트가 수용 가능한 미디어 타입
GET /api/users HTTP/1.1
Host: example.com
Accept: application/json, text/html
Accept-Language: ko-KR, en-US
Accept-Encoding: gzip, deflate, br
fetch('https://api.example.com/users', {
headers: {
'Accept': 'application/json',
'Accept-Language': 'ko-KR,ko;q=0.9,en;q=0.8',
'Accept-Encoding': 'gzip, deflate, br'
}
});
Accept 헤더 종류:
Accept
├─ Accept: application/json - JSON 선호
├─ Accept: text/html - HTML 선호
└─ Accept: */* - 모든 타입 허용
Accept-Language
├─ Accept-Language: ko-KR - 한국어 선호
└─ Accept-Language: en-US,en;q=0.9 - 영어도 가능 (우선순위 낮음)
Accept-Encoding
├─ Accept-Encoding: gzip - gzip 압축 지원
└─ Accept-Encoding: br, gzip - Brotli 선호, gzip도 가능
Accept-Charset (거의 사용 안 함)
└─ Accept-Charset: utf-8 - UTF-8 인코딩
Authorization
인증 정보
GET /api/profile HTTP/1.1
Host: example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
// JWT 토큰 인증
fetch('https://api.example.com/profile', {
headers: {
'Authorization': 'Bearer ' + token
}
});
// Basic 인증
const credentials = btoa('username:password');
fetch('https://api.example.com/profile', {
headers: {
'Authorization': 'Basic ' + credentials
}
});
인증 방식:
Bearer Token (가장 일반적)
Authorization: Bearer <token>
├─ JWT, OAuth 2.0에서 사용
└─ 예: Bearer eyJhbGci...
Basic Authentication
Authorization: Basic <base64-credentials>
├─ username:password를 Base64 인코딩
├─ 안전하지 않음 (HTTPS 필수)
└─ 예: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
API Key
Authorization: ApiKey <api-key>
또는
X-API-Key: <api-key>
Content-Type
요청 바디의 미디어 타입
POST /api/users HTTP/1.1
Host: example.com
Content-Type: application/json
{
"name": "홍길동",
"email": "hong@example.com"
}
// JSON 전송
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: '홍길동',
email: 'hong@example.com'
})
});
// 폼 데이터 전송
const formData = new FormData();
formData.append('name', '홍길동');
formData.append('file', fileInput.files[0]);
fetch('https://api.example.com/upload', {
method: 'POST',
body: formData
// Content-Type은 자동 설정 (multipart/form-data)
});
주요 Content-Type:
application/json
├─ JSON 데이터
└─ 가장 일반적인 API 형식
application/x-www-form-urlencoded
├─ 폼 데이터 (기본값)
└─ key1=value1&key2=value2
multipart/form-data
├─ 파일 업로드
└─ 여러 파트로 구성
text/plain
├─ 일반 텍스트
└─ 간단한 데이터
application/xml
├─ XML 데이터
└─ 레거시 API
Cookie
클라이언트가 저장한 쿠키 전송
GET /api/profile HTTP/1.1
Host: example.com
Cookie: sessionId=abc123; userId=456
// 브라우저가 자동으로 쿠키 전송
fetch('https://example.com/api/profile', {
credentials: 'include' // 쿠키 포함
});
Referer
이전 페이지 URL
GET /api/products/123 HTTP/1.1
Host: example.com
Referer: https://example.com/products
용도:
- 유입 경로 분석
- 보안 검증
- 로깅
기타 요청 헤더
Origin
├─ 요청이 시작된 오리진
└─ CORS 검증에 사용
If-None-Match
├─ ETag 값과 비교
└─ 캐시 검증
If-Modified-Since
├─ 날짜 이후 수정되었는지 확인
└─ 캐시 검증
Range
├─ 일부 데이터만 요청
└─ 예: bytes=0-1023
📤 응답 헤더 (Response Headers)
Content-Type
응답 바디의 미디어 타입
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
{
"id": 123,
"name": "홍길동"
}
fetch('https://api.example.com/users/123')
.then(response => {
console.log(response.headers.get('Content-Type'));
// "application/json; charset=utf-8"
return response.json();
});