Fetch API는 HTTP 파이프라인을 구성하는 요청과 응답 등 요소를 JavaScript에서 접근/조작할 수 있도록 한다. 즉, 전역 fetch() 메서드를 활용해 네트워크의 리소스를 비동기적으로 가져올 수 있다. fetch()는 브라우저 window 객체에 소속되어 있기 때문에 window.fetch()로 사용되기도 하며, 구식 브라우저에서 지원하지 않는다.(폴리필을 쓰면 사용이 가능하다.)
fetch()에는 HTTP 요청을 전송할 URL, HTTP 요청 메서드, HTTP 요청 헤더, 페이로드 등을 설정한 객체를 전달한다.fetch()는 2개의 인자를 받는다.
url : 접근하고자 하는 URLoptions : 선택 매개변수, method나 headers 등을 지정options이 없다면 GET 요청으로 진행된다.const promise = fetch(url, options)
readfetch()는 기본적으로 GET 방식으로 작동하고, options가 필요 없다.fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log(data))
createoptions의 method를 POST로 지정하고, headers로 JSON 포맷을 사용한다고 명시해야한다. 그리고, body에 요청 전문을 JSON 포맷으로 넣어준다.fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
body: "I am testing!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
updateoptions의 method를 PUT으로 설정하고, 나머지 포맷은 POST와 비슷하다.fetch("https://jsonplaceholder.typicode.com/posts", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
body: "I am testing!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
deletefetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "DELETE",
})
.then((response) => response.json())
.then((data) => console.log(data))
axios는 Promise API를 활용하는 HTTP 비동기 통신 라이브러리로, 백엔드와 프론트엔드가 통신을 쉽게하기 위해 Ajax와 더불어 사용한다.
axios의 장점
res.json()의 과정이 필요없다.npm install axios // npm 설치
yarn add axios // yarn 설치
axios({
url: '접근할 주소',
method: '메소드 종류(get, post 등)',
data: {
데이터 제목: '데이터 내용'
}
});
axios.get(url[, config])
axios.delete(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
readconst getList = async () => {
const { data } = await axios.get("요청할 주소")
console.log(data)
}
createconst postList = async () => {
try {
const { data } = await axios.post("요청할 주소", {
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
}
})
console.log(data);
} catch (error) {
console.log(error);
}
}
updateaxios.put("요청할 주소", "덮어쓸 값", config)
axios.patch("요청할 주소", "일부만 바꿀 값", config)
const updateList = async (newData) => {
const response = await axios.patch("요청할 주소", newData, {
headers: {
"Content-Type": "multipart/form-data"
}
});
return response
};
deleteconst deleteList = async (listId) => {
const { data } = await axios.delete(`요청할 주소/${listId}`)
console.log(data);
}
| 특징 | axios | fetch |
|---|---|---|
| 설치 필요 | 써드파티 라이브러리로 설치 필요 | 모던 브라우저 빌트인이라 설치 필요 없음 |
| XSRF 보호 | 해준다 | 별도 보호 없음 |
| 요청 시 사용 속성 | data 속성 사용 | body 속성 사용 |
| 데이터 처리 방식 | data는 object를 포함 | body는 문자열화 되어있다 |
| 성공 응답 판단 | status가 200이고 statusText가 'OK'이면 성공 | 응답객체가 ok 속성을 포함하면 성공 |
| 데이터 형식 변환 | 자동으로 JSON 데이터 형식으로 변환됨 | .json() 메서드를 사용해야 함 |
| 요청 취소 및 타임아웃 설정 | 요청을 취소할 수 있고 타임아웃 설정 가능 | 해당 기능 존재하지 않음 |
| HTTP 요청 가로챔 | 가능 | 기본적으로 제공하지 않음 |
| 다운로드 지원 | 기본적인 지원 있음 | 지원하지 않음 |
| 브라우저 지원 | 더 많은 브라우저에 지원됨 | Chrome 42+, Firefox 39+, Edge 14+, Safari 10.1+ 이상에 지원 |
fetch API Mdn
fetch API 모던 자바스크립트
fetch API 참고 사이트 1
fetch API 참고 사이트 2
axios 공식 문서
axios 참고 사이트 1