fetch()
가 반환하는 프로미스 객체는 HTTP 오류 상태(ex. 404, 500)를 수신해도 거부되지 않음fetch('http://example.com/movies.json')
.then((response) => response.json())
.then((data) => console.log(data));
fetch()
: 하나의 인수만 받고, 이는 가져오고자 하는 리소스의 경로를 나타냄Response
객체: HTTP 응답 전체를 나타내는 객체로, 직접 JSON 응답 본문을 받을 수는 없음json()
메서드를 호출해야함json()
메서드: 응답 본문 텍스트를 JSON으로 파싱한 결과로 이행하는, 또 다른 프로미스를 반환함브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리
Axios | Fetch API |
---|---|
써드파티 라이브러리로 설치가 필요함 | 빌트인 API라 별도의 설치 필요없음 |
자동으로 JSON데이터 형식으로 변환됨 | .json() 메서드를 사용해야 함 |
npm install axios
import axios from 'axios'
axios.get("url"[,config])
axios
.get('https://koreanjson.com/users/1')
.then((response) => {
const { data } = response; //자동으로 JSON데이터 형식으로 변환하기 때문에 .json() 필요 없음
})
.catch((error) => console.log(error));
axios.post("url"[, data[, config]])
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
참고자료
mdn - API
JavaScript Fetch API Ultimate Guide
Axios Docs - Post 요청