클라이언트가 서버에게 HTTP 통신을 통해 데이터를 요청하는 함수이다.
const res = await fetch(url);
// JSON 문자열을 파싱해서 js 객체로 변환
const data = await res.json();
console.log(data);
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);
리퀘스트에 관한 설정을 할 수 있다.
"GET", "POST", "PATCH", "DELETE" 등이 있고 기본값은 "GET""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는 브라우저, 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;
}