간단한 voca기능을 구현해보면서 fetch를 axios의 차이점을 정리하고 fetch에서 axios로 변경해보았습니다.
JSON.stringify()
를 사용하여 객체를 문자열으로 변환한 뒤 body
에 할당해야 합니다. fetch(`http://localhost:5000/words/${word.id}`, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8',
},
body: JSON.stringify({
...word,
isDone: !isDone,
}),
}).then((res) => {
if (res.ok) {
setIsDone(!isDone);
// let data = res.json();
}
});
await axios({
method: 'PUT',
url: `http://localhost:5000/words/${word.id}`,
data: { // 객체로 넘김
...word,
isDone: !isDone,
},
}).then((res) => {
if (res.statusText === 'OK') {
setIsDone(!isDone);
}
}).catch((e) => console.log(e));;
await axios
.put(`http://localhost:5000/words/${word.id}`, {
...word,
isDone: !isDone,
})
.then((res) => {
if (res.statusText === 'OK') {
setIsDone(!isDone);
// let data = res.data;
}
})
.catch((e) => console.log(e));
[데이터 넘기는 방법]
axios : 객체로 넘김
fetch : string화 해서 넘김
[정상적인 요청/응답 체크]
axios : statusText를 통해서 확인
fetch : response 객체가 ok프로퍼티를 포함하는지 확인
[response 얻는 방법]
axios : response 객체의 data property에 접근하여 얻는다.
fetch : response 객체에 .json() 메소드를 호출하여서 json객체를 얻는다.