fetch와 axios로 Http 요청을 보낼때에는 늘 promise를 반환하는데, response 객체를 promise로 감싸서 반환한다. 이후 후속 메서드를 활용하면 resolve된 값으로 사용할 수 있는 것..
즉 후속메서드는 늘 resolve된 값을 사용한다!! (rejected때는 생각하지 않고 적엇읍니다.)
fetch('https://example.com/data.json') // response 객체를 promise로 감싸서 반환함
.then(response => response.json()) // resolve된 response 객체를 활용 근데 json해줌
.then(data => console.log(data)) // json하면 프로미스 반환함, 반환된거 resolve하면 이제서야 data로 변환됨
.catch(error => console.error(error));
fetch > 프로미스 반환 > resolve되면 response 객체로 됨 > response객체 가지고 .json()메서드 사용 그럼 프로미스로 반환함 > 다음 후속 메서드에서 프로미스 resolve되면 원하는 json파일로 완성!
그래서 일반적으로 fetch는 늘 두번의 then을 활용한다고 한다. 하지만, axios 같은경우는 then 처리를 두번할 필요 없이 자동적으로 json 데이터 포맷으로 활용할 수 있다. fetch 와 다르게 get, post, delete, put, patch 메서드를 사용할 수 잇음.
그리고 fetch 같은 경우 put, pach를 할 때 보내줄 데이터를 stringify하는 작업이 필요하지만, axios같은 경우 자동적으로 데이터를 문자열로 바꿔준다.
axios
const url = "https://jsonplaceholder.typicode.com/todos";
const todo = {
title: "A new todo",
completed: false,
};
axios
.post(url, {
headers: {
"Content-Type": "application/json",
},
data: todo,
})
.then(console.log);
fetch
const url = "https://jsonplaceholder.typicode.com/todos";
const todo = {
title: "A new todo",
completed: false,
};
fetch(url, {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(todo),
})
.then((response) => response.json())
.then((data) => console.log(data));