Web
개발자가 알아야 할 HTTP 기초
HTTP의 기본 개념부터 헤더, 캐싱, CORS까지. 웹 개발자라면 알아야 할 HTTP 지식을 정리합니다.
HTTP는 웹의 기반 프로토콜입니다. 프론트엔드와 백엔드 모두 HTTP를 이해해야 원활한 통신이 가능합니다.
HTTP 요청과 응답
[요청]
GET /api/users/123 HTTP/1.1
Host: api.example.com
Accept: application/json
Authorization: Bearer eyJhbGc...
[응답]
HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: max-age=3600
{"id": 123, "name": "홍길동"}
HTTP 메서드
GET - 리소스 조회 (읽기)
POST - 리소스 생성
PUT - 리소스 전체 교체
PATCH - 리소스 부분 수정
DELETE - 리소스 삭제
HEAD - 헤더만 조회
OPTIONS - 허용된 메서드 확인
멱등성 (Idempotency)
같은 요청을 여러 번 보내도 결과가 같으면 멱등합니다.
GET - 멱등 (여러 번 조회해도 같은 결과)
PUT - 멱등 (같은 데이터로 여러 번 교체해도 결과 동일)
DELETE - 멱등 (이미 삭제된 리소스 삭제 시도해도 결과 동일)
POST - 멱등 아님 (호출할 때마다 새 리소스 생성)
PATCH - 멱등 아닐 수 있음 (구현에 따라 다름)
상태 코드
2xx 성공
200 OK - 성공
201 Created - 리소스 생성됨
204 No Content - 성공했지만 반환할 내용 없음
3xx 리다이렉션
301 Moved Permanently - 영구 이동 (캐시됨)
302 Found - 임시 이동
304 Not Modified - 캐시 사용
4xx 클라이언트 에러
400 Bad Request - 잘못된 요청
401 Unauthorized - 인증 필요
403 Forbidden - 권한 없음
404 Not Found - 리소스 없음
405 Method Not Allowed - 허용되지 않은 메서드
409 Conflict - 충돌
422 Unprocessable Entity - 유효성 검사 실패
429 Too Many Requests - 요청 횟수 초과
5xx 서버 에러
500 Internal Server Error - 서버 오류
502 Bad Gateway - 게이트웨이 오류
503 Service Unavailable - 서비스 불가
504 Gateway Timeout - 게이트웨이 타임아웃
중요한 헤더
요청 헤더
Content-Type: application/json
Accept: application/json
Authorization: Bearer <token>
Cookie: session=abc123
User-Agent: Mozilla/5.0 ...
Origin: https://mysite.com
응답 헤더
Content-Type: application/json
Set-Cookie: session=abc123; HttpOnly; Secure
Cache-Control: max-age=3600
Access-Control-Allow-Origin: https://mysite.com
캐싱
Cache-Control
# 1시간 동안 캐시
Cache-Control: max-age=3600
# 캐시 금지
Cache-Control: no-store
# 캐시하되 매번 검증
Cache-Control: no-cache
# 공유 캐시 허용 (CDN)
Cache-Control: public, max-age=86400
# 개인 캐시만 (브라우저)
Cache-Control: private, max-age=3600
조건부 요청
# 서버 응답
ETag: "abc123"
Last-Modified: Wed, 01 Jan 2026 00:00:00 GMT
# 클라이언트 재요청
If-None-Match: "abc123"
If-Modified-Since: Wed, 01 Jan 2026 00:00:00 GMT
# 변경 없으면 304 반환 (본문 없이)
CORS (Cross-Origin Resource Sharing)
다른 출처(도메인, 포트, 프로토콜)로의 요청을 제어합니다.
단순 요청
GET, POST, HEAD이고 특별한 헤더가 없으면 단순 요청입니다.
# 요청
GET /api/data HTTP/1.1
Origin: https://mysite.com
# 응답
Access-Control-Allow-Origin: https://mysite.com
Preflight 요청
복잡한 요청 전에 OPTIONS 요청으로 허용 여부를 확인합니다.
# Preflight 요청
OPTIONS /api/data HTTP/1.1
Origin: https://mysite.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type, Authorization
# Preflight 응답
Access-Control-Allow-Origin: https://mysite.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
쿠키와 CORS
// 클라이언트
fetch(url, {
credentials: 'include' // 쿠키 포함
});
// 서버 응답 헤더
Access-Control-Allow-Origin: https://mysite.com // * 불가
Access-Control-Allow-Credentials: true
Content-Type
# JSON
Content-Type: application/json
# 폼 데이터
Content-Type: application/x-www-form-urlencoded
# 파일 업로드
Content-Type: multipart/form-data
# HTML
Content-Type: text/html; charset=utf-8
fetch API 예시
// GET
const response = await fetch('/api/users');
const users = await response.json();
// POST
const response = await fetch('/api/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ name: '홍길동' })
});
// 에러 처리
if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
}
마무리
HTTP를 이해하면 디버깅이 쉬워지고, API 설계도 잘할 수 있습니다. 브라우저 개발자 도구의 네트워크 탭을 자주 확인하면서 실제 요청/응답을 살펴보는 것을 추천합니다.