[React, HTTP] application/json vs multipart/form-data vs application/x-www-form-urlencoded

SihoonCho·2023년 3월 29일
0
post-thumbnail

📌 Content-Type


HTTP REQUEST의 구조

  • API 연동시에 전송할 자원을 명시하기 위해 사용
  • HTTP Header에 명시하는 Message Body에 들어갈 Body(데이터)Type
  • application/json, multipart/form-data, application/x-www-urlencoded

React, How to use

import axios from "axios";

axios.post({url}, {data}, {
  headers: {
    "Content-Type": "application/json",						// 대체로 많이 사용
	"Content-Type": "multipart/form-data",					// 첨부파일, 이미지
    "Content-Type": "application/x-www-form-urlencoded",	// Default
  },
}).then((response) => {
  console.log(response);
}).catch((error) => {
  console.log(error);
});

📖 application/json


  • RESTful API 구현에 JSON을 많이 사용
  • JSON 은 배열 및 복잡한 데이터 구조를 간결하게 표현
  • JSON 사용에 따라 일반적으로 많이 사용되는 Content-Type
  • { "Content-Type": "application/json" }

React, Data

const data = {
  id: id,
  title: title,
  content: content,
}

React, POST REQUEST

import axios from "axios";

axios.post("http://localhost:8080/api/post", JSON.stringify(data), {
  headers: {
    "Content-Type": "application/json",		// 일반적으로 많이 사용
  },
}).then((response) => {
  console.log(response);
}).catch((error) => {
  console.log(error);
});

📖 multipart/form-data


  • 파일이나 이미지를 전송할 때 주로 사용
  • 파일이나 이미지를 문자로 생성하여 HTTP request body에 담아 서버로 전송
  • { "Content-Type": "multipart/form-data" }

HTTP Request Body가 한 종류의 Type인 경우가 대부분이고,
Content-Type도 마찬가지로 한 종류만 명시 가능

파일을 업로드하는 상황의 경우 이미지 설명에 대한 input과 이미지 파일에 대한 input 필요
이미지 설명에 대한 inputContent-Typeapplication/x-www-form-urlencoded,
이미지 파일에 대한 inputContent-Typeimage/png일 것

HTTP Request body에 두 종류의 Content-Type
구분해서 넣어줄 방법이 필요해서 multipart라는 개념을 사용

React, Data

const data = {
  id: id,
  title: title,
  content: content,
}

const [files, setFiles] = useState([]);
const onChangeFiles = async (e) => {
  e.preventDefault();
  setFiles(e.target.files);
}

React, POST REQUEST

const formData = new FormData();

// 다중 첨부파일 삽입
for (let i = 0; i < files.length; i++) {
  formData.append("files", files[i]);
}

// 텍스트 데이터 삽입
formData.append("data", new Blob([JSON.stringify(data)], {
  type: "application/json",
}));

// POST 요청
await axios.post("http://localhost:8080/api/post", formData, {
  headers: {
    "Content-Type": "multipart/form-data",
  },
}).then((response) => {
  console.log(response);
}).catch((error) => {
  console.log(error);
});

📖 application/x-www-form-urlencoded


  • html form submitDefault Content-Type
  • QueryString(key1=value1&key2=value2) 형태로 전달
  • 요즘은 자주 사용되지는 않지만, 여전히 종종 사용하는 경우가 있음
  • 데이터를 URL Encoding 방식으로 인코딩 후 웹서버로 전달하는 방식
  • 사용하는 LibraryFramework에서 Body Encoding을 지원하는지 확인필요
  • { "Content-Type": "application/x-www-form-urlencoded" }

React, Data

const data = {
  id: id,
  title: title,
  content: content,
}

React, POST REQUEST

$ npm install qs
import qs from "qs";
import axios from "axios";

axios.post(url, qs.stringify(data), {
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",	// Default
  },
}).then((response) => {
  console.log(response);
}).catch((error) => {
  console.log(error);
});

어차피 default header를 사용할 것이라면,
axios 기본 POST REQUEST를 사용하는 것이 좋을 것 같다.

React, POST REQUEST

import axios from "axios";

axios.post("http://localhost:8080/api/post", data)
.then((response) => {
  console.log(response);
}).catch((error) => {
  console.log(error);
});


Reference

https://jw910911.tistory.com/117
https://velog.io/@483759/x-www-form-urlencoded%EC%99%80-applicationjson%EC%9D%98-%EC%B0%A8%EC%9D%B4-HTTP-Content-Type

profile
꾸준히 노력하는 개발자

0개의 댓글