개발/웹
[리뷰] Fetch, Axios
z-zero
2022. 5. 31. 12:30
비동기 요청의 가장 대표적인 사례는 단연 네트워크 요청이다. 그중에서 URL로 요청하는 경우가 가장 흔한데, 이것을 가능하게 해 주는 API가 바로 fetch API이다.
fetch API
// Promise ver
let url = "URL주소";
fetch(url)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.log(error));
// Async/Await ver
let url = "URL주소";
async function request(){
const response = await fetch(url);
}
request()
Axios
Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리이다. fetch API보다 사용이 간편하면서 추가적인 기능들이 포함되어 있다.
Fetch API | Axios |
빌트인 API라 별도의 설치가 필요 없음 | 써드파티 라이브러리로 설치가 필요 |
.json() 메서드를 사용해야 함 | 자동으로 JSON데이터 형식으로 변환 됨 |
// 사용법
npm install axios
axios.get("url"[, config])
axios.post("url"[, data[, config]])
// get
// fetch
fetch('URL', { method: 'GET' })
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.log(error));
// axios
import axios from 'axios';
axios
.get('URL')
.then((response) => {
const { data } = response;
console.log(data);
})
.catch((error) => console.log(error));
// post
// fetch
fetch('URL', {
method: 'POST',
headers: {
// JSON의 형식으로 데이터를 보내준다고 서버에게 알려주는 역할
'Content-Type': 'application/json',
},
body: JSON.stringify({ nickName: 'abc', age: 20 }),
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.log(error));
// axios
import axios from 'axios';
axios
.post('URL', { nickName: 'abc', age: '20' })
.then((response) => {
const { data } = response;
console.log(data);
})
.catch((error) => console.log(error));