API, fetch
API과 호출 방법에 대해 알아본다.
Aplication Programming Interface
클라이언트와 서버 간 연결 방법
API 호출: API를 통해 데이터 요청(request)와 전달(response)과 같은 일련의 과정을 일컬음.
open API를 사용할 것이다.
먼저, 다음 주소로부터 JSON 형식의 response를 받을 것이다.
https://jsonplaceholder.typicode.com/posts
다음 코드를 입력한다.
let response = fetch("<https://jsonplaceholder.typicode.com/posts>").then((res) =>
console.log(res)
);
fetch
함수는 인자로 API 주소를 받으며, promise 객체를 반환한다. .then
을 이용하여 결과값을 출력하면 response 객체를 보낸다.
JSON 형식으로 response 파일을 받아내기 위해서는 다음 코드를 작성한다.
async function getData() {
let rawResponse = await fetch("<https://jsonplaceholder.typicode.com/posts>");
let jsonResponse = await rawResponse.json();
console.log(jsonResponse);
}
getData();