HTTP 헤더는 클라이언트와 서버가 주고받는 메타데이터입니다.
우리가 택배를 보낼 때 송장에 받는 사람 정보, 주의사항 등을 적는 것처럼, HTTP 통신에서도 부가 정보가 필요합니다.
headers: {
"Content-Type": "application/json"
}
headers: {
"Authorization": "Bearer eyJhbGciOiJIUzI1..."
}
headers: {
"Accept": "application/json"
}
const axiosInstance = axios.create({
baseURL: "https://api.example.com",
headers: {
"Content-Type": "application/json" // 모든 요청에 적용될 기본 헤더
}
});
// 로그인 요청
axiosInstance.post('/auth/login', loginData, {
headers: {
"Client-Version": "1.0.0" // 특정 요청에만 필요한 헤더
}
});
// 파일 업로드
axiosInstance.post('/upload', formData, {
headers: {
"Content-Type": "multipart/form-data" // 기본 헤더 덮어쓰기
}
});
// JSON 요청용
const jsonInstance = axios.create({
headers: { "Content-Type": "application/json" }
});
// 파일 업로드용
const uploadInstance = axios.create({
headers: { "Content-Type": "multipart/form-data" }
});
// 일반 API용
const apiInstance = axios.create({
headers: { "Authorization": `Bearer ${token}` }
});
// 외부 API용
const externalInstance = axios.create({
headers: { "API-Key": "external-api-key" }
});
HTTP 헤더는 API 통신에서 중요한 역할을 합니다.
데이터의 형식을 명시하고, 인증 정보를 전달하며, 추가적인 메타데이터를 제공합니다.
적절한 헤더 설정은 안정적인 API 통신의 기본이 됩니다.
때로는 다른 설정의 axios 인스턴스가 필요할 수 있습니다.
이는 코드의 재사용성을 높이고 유지보수를 쉽게 만듭니다. 하지만 너무 많은 인스턴스는 오히려 복잡성을 증가시킬 수 있으므로, 실제로 필요한 경우에만 생성하는 것이 좋습니다.