[Study/Web] Content-Type header

SoShy·2024년 1월 29일
0

웹 개발

목록 보기
7/21
post-thumbnail

1. Content-Type header


request와 response는 둘 다 head와 body로 이루어져 있으며, head에는 각종 부가 정보들이, body에는 실제 데이터가 담겨있다.

또한, head에는 다양한 header들이 존재하는데, 본 글에서는 Content-Type header에 대해 알아보도록 하자.

Content-Type header는 현재 request 또는 response의 body에 들어 있는 데이터가 어떤 타입인지를 나타낸다.

request 또는 response의 body에는 HTML이나 JavaScript 코드, JSON 데이터 외에도 굉장히 다양한 종류의 데이터가 들어갈 수 있으며, 이런 데이터들의 타입 정보가 바로 Content-Type header에 담기는 것이다.

Content-Type header의 값은 주 타입(main type)/서브 타입(sub type)의 형식으로 나타내며, 앞으로 흔히 만나게 될 Content-Type header의 값으로는 다음과 같은 것들이 있다.

1. 주 타입이 text인 경우

  • 일반 텍스트 : text/plain
  • CSS 코드 : text/css
  • HTML 코드 : text/html
  • JavaScript 코드 : text/javascript

2. 주 타입이 image인 경우

  • image/bmp : bmp 이미지
  • image/gif : gif 이미지
  • image/png : png 이미지

3. 주 타입이 audio인 경우

  • audio/mp4 : mp4 오디오
  • audio/ogg : ogg 오디오

4. 주 타입이 video인 경우

  • video/mp4 : mp4 비디오
  • video/H264 : H264 비디오

5. 주 타입이 application인 경우

  • application/json : JSON 데이터
  • application/octet-stream : 확인되지 않은 바이너리 파일

text, image, audio, video의 네 가지 타입에 속하지 않는 것들은, 보통 application에 속하며, application/json 값이 JSON 데이터를 나타낸다.

바이너리 파일(binary file)이란 텍스트 파일 이외의 파일들을 의미하며, 그 중에서도 특정 확장자 포맷에 해당하지 않는 데이터들을 application/octet-stream으로 나타낸다.

참고로, 브라우저는 response의 Content-Type header의 값으로 application/octet-stream이 쓰여 있으면, 보통 사용자에게 '다운로드 받으시겠습니까?'와 같은 alert 창을 띄운다.

이 외에 Content-Type header 값으로 들어갈 수 있는 데이터 타입이 궁금하다면 다음 링크를 참고하자.

Content-Type header는, body의 데이터를 직접 확인하지 않고도 그 타입을 확인하기 위해 존재한다.

만약, request의 body에 데이터를 담아 보낼 때, head에서 Content-Type의 값을 제대로 입력해주지 않는다면, 서버에서 body 의 데이터가 어떤 타입인지를 확인하는 절차가 추가적으로 필요해지고, 이로 인해 불필요한 비용이 발생하게 된다.

때문에, request와 response 모두 body에 어떤 데이터가 존재한다면 Content-Type header의 값을 적절하게 설정해주는 것이 바람직하다.



2. Content-Type 설정하기


const newMember = {
  name: 'Jerry',
  email: 'jerry@codeit.kr',
  department: 'engineering',
};

fetch('http://learn.codeit.kr/api/members', {
  method: 'POST',
  body: JSON.stringify(newMember),
})
  .then((response) => response.text())
  .then((result) => { console.log(result); });

위 코드를 기반으로, Content-Type header 값을 설정한 코드는 아래와 같다.
const newMember = {
  name: 'Jerry',
  email: 'jerry@codeit.kr',
  department: 'engineering',
};

fetch('https://learn.codeit.kr/api/members', {
  method: 'POST',
  headers: { // 추가된 부분
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(newMember),
})
  .then((response) => response.text())
  .then((result) => { console.log(result); });
profile
프론트엔드 개발자가 되기 위해 노력 중인 새싹🌱 입니다.

0개의 댓글

관련 채용 정보