[JavaScript] fetch와 axios

뽕칠이·2024년 6월 26일

fetch

클라이언트가 서버에게 HTTP 통신을 통해 데이터를 요청하는 함수이다.

const res = await fetch(url);
// JSON 문자열을 파싱해서 js 객체로 변환
const data = await res.json();

console.log(data);

URL 객체

const params = {offset: 10, limit: 10};
const url = new URL("주소");
// url에 지정된 파라미터를 추가
Object.keys(params).forEach((key) => url.searchParams.append(key, params[key]));

const res = await fetch(url);
const data = await res.json();

console.log(data);

fetch 옵션

리퀘스트에 관한 설정을 할 수 있다.

  • method : "GET", "POST", "PATCH", "DELETE" 등이 있고 기본값은 "GET"
  • body : JSON 형태로 변환하여 전달
  • headers : "Content-Type"을 주로 사용
const data = {
	mbti : "ESTJ",
    colorCode : "#000000",
    password : "0000"
};

// 해당 주소에 data 전달
const res = fetch("주소", {
	method : "POST",
    body : JSON.stringify(data),
    headers : {"Content-Type" : "application/json"}
});

const resData = res.json();
console.log(resData);

axios

axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리이다.

별도의 설치가 필요하지만 fetch보다 더 많은 기능을 제공하고 문법을 간소화할 수 있다.

async function getColorSurvey(id){
	const res = await axios.get(`https://learn.codeit.kr/api/color-surveys/${id}`);
  	return res.data;
}

0개의 댓글