fetch(url, options)
.then((response) => console.log("response:", response))
.catch((error) => console.log("error:", error));
JSON Placeholder의 공개된 API를 사용해서 예제 코드를 작성해보자
fetch() 함수는 디폴트로 GET 방식으로 작동하고 GET 방식은 요청 전문을 받지 않기 때문에 옵션 인자가 필요없다.
fetch("https://jsonplaceholder.typicode.com/posts/1").then((response) =>
console.log(response)
);
Response {status: 200, ok: true, redirected: false, type: "cors", url: "https://jsonplaceholder.typicode.com/posts/1", …}
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log(data));
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"
}
fetch("https://jsonplaceholder.typicode.com/posts", option)
.then(res => res.text())
.then(text => console.log(text));
//await은 async함수내에서만 쓸수 있으니, 익명 async 바로 실행함수를 통해 활용한다.
(async () => {
let res = await fetch("https://jsonplaceholder.typicode.com/posts", option);
let text = res.text();
console.log(text);
})()
fetch() 함수는 사용법이 아주 간단하지만, 계속 사용하다보면 똑같은 코드가 반복된다는 것을 알수있다.
예를 들어, 응답 데이터을 얻기 위해서 response.json()을 매번 호출하거나, 데이터를 보낼 때, HTTP 요청 헤더에 "Content-Type": "application/json"로 일일히 설정해줘야 되거나 써야 될게 많다.
1, 2번 fetch() 를 사용하는 정도는 문제가 안되지만, 여러번 사용할 일이 있으면 따로 헬퍼 함수를 만들어 모듈화를 해놓는게 나중에 정말 편하게 사용할수 있다.