
이번에 진행한 위스타그램에서 백엔드 서버와 통신을 하면서 사용했던
fectch와axios에 대해 간단히 공부해보겠습니다.
자바스크립트를 사용한 비동기 통신이며, 클라이언트와 서버와 데이터를 xml형태로 주고받는 통신방법이다.
쉽게 말해서 자바스크립트를 사용해서 서버에 데이터를 요청하는 것!
비동기?? : 데이터를 받아오는 시간동안 대기하지 않고 바로 바로 다음 로직을 수행하는 것
import해서 사용하지 않아도 된다.body에 객체를JSON 문자열로 변환해주는 과정이 필요하다.response를 json으로 변환해주는 과정이 필요하다.fetch('url', {
method : 'POST',
body : JSON.stringify({
user:this.state.loginId,
password: this.state.loginPw
})
}).then((res) => res.json())
.then((res) => res.status)
fetch('url', {
method:'GET'
}).then((res) => res.json()).then((res) => res.status)
fetch('url',{}).then((res) => res.json()).then((res) => res.status)
fetch의 default method는 "GET" 이므로 생략이 가능하다.
axios.post('url', {
user: this.state.username
password: this.state.password
})
.then ( (res) => res.status)
.catch ( (error ) => error)
axios.get('http://localhost:3000/data/mainContentObj.json')
.then(res => {
this.setState({
mainContentObj: res.data
});
});
fetch 성공시 넘어오는 res

axios 성공시 넘어오는 res

axios 같은 경우 요청 성공시 config,data,headers,status 값등이 넘어오는 반면에 fetch 는 요청 성공시 넘어오는 json 객체 값만 넘어온다.