Content-Type

형진·2022년 4월 19일
0

node

목록 보기
2/8

RestAPI의 경우 보통 JSON타입으로 요청하고, 요청을 받는다. 그래서 당연히 application/json 타입으로 Content-Type 사용한다고 생각을 하는 경우가 많은데, 자료를 찾다보니 그렇지 않다는걸 알게되었다.

html form 태그를 사용하여 post 방식으로 요청하거나, jQuery의 ajax 등의 요청을 할때 default Content-Type은 'application/json'이 아니라 'application/x-www-form-urlencoded'다.

아래와 같은 코드로 client에서 server로 요청을 보낸다고 해보자.

Content-Type에 따라서 client에서 server로 보내는 데이터의 형식이 달라진다.

const data = {
    "name": "kim",
    "age": 29
}

axios({
    method: 'post',
    url: 'https://localhost:8080',
    headers: {
        'Content-Type': ....
    },
    data: data
}).then((res) => {
    // handle success
}).catch((err) => {
    // handle error
}).then(() => {
    // always
})
  • application/x-www-form-urlencoded :

x-www-form-urlencoded의 경우, 아래와 같이 key1=value1&key2=value2 의 형식으로 요청이 가고 있다.

POST / HTTP/1.1
Host: localhost
Content-Type: application/x-www-form-urlencoded

name=kim&age=29
  • application/json :

json의 경우, 아래와 같이 json 형태로 요청이 가는걸 볼수 있다.

POST / HTTP/1.1
Host: localhost
Content-Type: application/json

{
  "name":"kim",
  "age":"29"
}

headers: { ‘content-Type': 'application/json' }

headers: { accept: 'application/json' }

이렇게 두가지 방식으로 쓸 수 있는데, 구체적인 차이점이 궁금했다.

두개의 차이점?

Content-Type 헤더와 Accept 헤더 둘 다 데이터 타입(MIME)을 다루는 헤더이지만,Content-Type 헤더는 현재 전송하는 데이터가 어떤 타입인지에 대한 설명이고,Accept 헤더는 클라이언트가 서버에게 웬만하면 데이터 전송할때 이러이러한 타입으로 가공해서 보내라 라고 하는 것이라고 이해하면 된다.

출처

profile
느낀대로 적자

0개의 댓글

관련 채용 정보