fetch 간단 활용법 정리
Fetch API
The Fetch API provides an interface for fetching resources (including across the network). It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.
developer.mozilla.org
fetch사용시 유의 사항 (json() 함수 사용하기) · 쾌락코딩
fetch사용시 유의 사항 (json() 함수 사용하기) 25 Nov 2018 | javascript network basic js 개발자들은 network request 요청이 필요할 경우 대부분 axios.js나 기타 다른 라이브러리를 쓰는 것 같다. js에서 기본적으로 제공하는 fetch라는 함수가 있지만, fetch를 사용할 경우 응답받은 body데이터의 form을 직접 변환해야 하는데, 이 단계를 자동으로 해주기 때문이고, 에러 핸들링도 편하기
wooooooak.github.io
* fetch는 브라우저에서 기본으로 제공하는 api이지만 node에서는 기본 제공되지 않는다. node-fetch 패키지를 설치한 이후에 fetch를 사용할 수 있는데 이럴 거면 그냥 axios 쓰고 만다. 가볍게 브라우저만을 활용한다고 가정하고 글을 읽자.
호환성으로도 axios가 더 우위에 있지만, 간단하게 fetch를 사용하는 방법을 알아보자.
GET
axios가 자동으로 json 변환을 해주는 반면 fetch는 그렇지 않아서 백단에서 건너온 res를 json화 해주어야 합니다.
const fetchTest = () => {
return (
// fetch 실행시 프로미스 반환
fetch("https://api.coinpaprika.com/v1/coins")
// 받은 정보를 json와 합니다.
.then((res) => res.json())
// json을 출력합니다.
.then((json) => console.log(json))
// 에러 핸들러
.catch((error) => console.log(error))
);
};
fetchTest();
POST
// 보낼 정보
const obj = {
body: [
{ id: 1, name: "darren" },
{ id: 2, name: "martin" },
],
headers: {},
method: "POST",
};
// 백단의 주소
const URL = "http://localhost:5000"
fetch(URL, obj)
.then(res => res => res.json())
.then(json => console.log(json))
.catch(err => console.log(err));