비동기 요청은 Promise 객체를 이용해서 구현해봤다. 비동기 요청 중 대표적인 사례는 네트워크 요청이다.
특정 URL로부터 정보를 받아오는 역할을 한다. 역시 비동기로 실행된다.
let url = "https://~~~"
fetch(url)
.then((response) => response.json())
.then((data) => console.log(data))
.catch()
위 코드가 기본적인 형태다.
두 번째 매개변수도 제공할 수 있다.
async function postData(url, data) {
const response = await fetch(url, {
method: "POST",
mode:
cache:
credentials:
headers: {
'Content-Type': application/json'
}
redirect:
referrerPolicy:
body: JSON.stringify(data)
})
return response.json();
}
postData(url, data).then((data) => {
console.log(data);
})
fetch API와 비슷한 역할을 하는 라이브러리다. Node.js를 위한 Promise API를 활용한 HTTP 비동기 통신 라이브러리다. Node.js 에서는 http 모듈을 사용하고 클라이언트(브라우저)에서는 XMLHttp Requests를 사용한다.
$ npm install axios
내장 라이브러리 fetch API랑 다르게 Axios는 써드 파티 라이브러리이기 때문에 설치 해야 한다.
axios.get("url"[,config])
일단 fetch API와 Axios를 쓸건데 Promise Async/Await 방식 두가지로 나눠서 쓸거다.
// Promise ver.
fetch()
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.log(error))
// Async / Await ver.
async function request() {
const response = await fetch(url, { method:"GET" })
const data = await response.json();
console.log(data)
}
request();
import axios from "axios";
// Promise ver.
axios
.get(url)
.then((response) => {
console.log(response);
const { data } = response;
console.log(data);
})
.catch((error) => console.log(error))
// Async / Await ver
async function request() {
const response = await axios.get(url);
const { data } = response;
console.log(data);
}
request();
fetch API는 response에 먼저 담았다가 response.json()의 리턴값이 data값이 된다.
반면, Axios는 response 단계에서 reponse와 data를 둘다 불러올 수 있다. fetch API보다는 Promise 단계를 한번 덜 한다고 볼 수 있다.
참고
fetch API
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch
Axios 기본 예제
https://axios-http.com/kr/docs/example