client와 server간에 상호작용을 하는 것으로 데이터 요청(Request)와 요청 데이터를 전달(Response)의 과정을 말한다.
client와 server가 대화를 하는 방법
즉, 다른 프로그램에게 말을 거는 것과 비유할 수 있다.
API 호출은 데이터를 반환받기 위한 목적이 있다.
하지만 응답을 언제 받을지 확실히 알 수 없다. API호출은 우리 컴퓨터 안에서 이루어지지 않을 수 있고, client컴퓨터와 server컴퓨터가 다를 수도 있다.
우리가 요청한 데이터를 응답해주는 시간은 인터넷 연결 속도, 서버의 부하상태 등에 따라 예상할 수 없고, 때로는 실패하는 경우(그래서 Promise객체에 reject가 있는 이유이기도 하다.)도 있다.
API호출은 응답의 시간을 예상할 수 없으므로 동기 호출이 아닌 비동기 호출
로 응답을 받아낸다.
API를 호출할 수 있도록 도와주는 JS엔진 내장함수
let response = fetch("https://jsonplaceholder.typicode.com/posts").then(
(res) => {
console.log(res);
}
);
Response {type: "cors", url: "https://jsonplaceholder.typicode.com/posts", redirected: false, status: 200, ok: true…}
type: "cors"
url: "https://jsonplaceholder.typicode.com/posts"
redirected: false
status: 200
ok: true
statusText: ""
headers: Headers
body: ReadableStream
bodyUsed: false
arrayBuffer: ƒ arrayBuffer() {}
blob: ƒ blob() {}
clone: ƒ clone() {}
formData: ƒ formData() {}
json: ƒ json() {}
text: ƒ text() {}
<constructor>: "Response"
즉, API 데이터의 택배상자 통째로 받은 격이다.
async function getData() {
let rawResponse = await fetch("https://jsonplaceholder.typicode.com/posts");
let jsonResponse = await rawResponse.json();
console.log(jsonResponse);
}
getData();
(100) [Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, …]