스터디17일차 - Fetch API, Axios
288. Fetch API : JavaScript를 이용해 HTTP 요청을 만드는 최신 방식
XHR대신 AJAX가 인기를 끌게 됩니다. 비동기 요청방식으로, 동적 화면을 만들고 새로고침을 하지 않아도 됩니다.
fetch('https://주소')
올바른 주소라면 promise 상태 resolved를 반환하고
올바르지 않은 주소라면 promise 상태 rejected를 반환합니다.
fetch('https://주소')
.then(res => {
console.log("response", res) // 주소로부터 응답을 받습니다.
return res.json() // 주소로부터 받은 데이터를 JS로 이용할 수 있도록 parsing합니다.
})
.then(data => {
console.log("Parsing Data", data.ticker.price) // 데이터의 속성에 접근하여 이용합니다.
})
.catch(e => {
console.log("error", e) // 문제가 있다면 에러를 출력합니다.
})
Axios 함수는 "Fetch로 요청을 생성"하고 "JSON으로 분석"하는 두 과정을 한번에 합니다.
axios
.get("https://주소")
.then((res) => {
console.log(res);
});
.catch((e) => {
console.log(e);
});
보통 async 비동기 함수와 함께 사용합니다.
const getData = async (id) => {
try {
const res = await axios.get(`http://주소이름/${id}`); // res 변수에 데이터를 저장합니다.
console.log(res.data);
} catch (e) {
console.log("ERROR", e); // rejected 되었다면 출력합니다.
}
};
getData(1);