fetch와axios둘다 결국에는 서버와 통신하기 위해 사용하는 방법 중 하나일 뿐이다. 기능적으로는 동일하지만, 사용하는 방식이 다르다. 지난번엔fetch를 사용해서, 이번에는axios를 사용해봤는데 둘다 사용해보고 비교해보니axios가 조금은 더 편한 것 같다.
fetch(API, {
headers: {
Authorization: sessionStorage.getItem("access_token"),
},
})
.then((res) => res.json())
.then((res) => {
this.setState({
stateName: res.data;
});
});
}
axios.get(API, {
headers: {
"Content-Type": "application/json",
Authorization: response.access_token,
},
})
.then((res) => {
this.setState({
stateName: res.data.data;
});
});
위 두개는 각각 fetch와 axios를 통해 headers에 정보를 담아 서버에 보내주는 것이다.
fetch는 들어오는 res를 그대로 사용하면 되지만, axios는 res.data로 사용해야 한다.fetch는 들어오는 값이 json형식이기 때문에 javascript형식으로 바꿔줘야 되지만, axios는 별도의 작업이 필요하지 않다.axios는 headers에 정보를 보낼 때, 'Content-Type'을 지정해줘야 한다.