브라우저에서 fetch 함수를 지원하기 이전에는 API 호출을 위해서 request
나 axios
와 같은 라이브러리들을 주로 사용해왔다. 하지만 요즘에는 이런 라이브러리의 도움 없이 브라우저에 내장된 fetch 함수를 사용해도 충분한 경우가 많기 때문에 오히려 라이브러리를 사용하는 것이 자바스크립트 번들(Bundle)의 크기만 늘려서 낭비가 될 수도 있다.
fetch(url, options)
.then((response) => console.log("response:", response))
.catch((error) => console.log("error:", error))
url
: 접근하고자하는 URLoptions
: HTTP 방식(method), HTTP요청 헤더(headers), HTTP 요청 전문(body)등을 지정할 수 있고 디폴트 값은 GET 메서드이다.response.text()
: 응답을 읽고 텍스트로 반환response.json()
: 응답을 jSON으로 파싱response.formData()
: 응답을 FormData 객체 형태로 반환response.blob()
: 응답을 Blob(타입이 있는 바이너리 형태)으로 반환response.arrayBuffer()
: 응답을 arrayBuffer(바이너리를 로우 레벨 형식으로 표현)으로 반환GET 방식은 request body 부분이 필요 없기 때문에 따로 두 번째 매개 변수인 options가 필요없다.
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"
}
POST 방식은 method를 POST, headers 옵션을 JSON 포맷으로 지정해야하며 request body를 JSON으로 직렬화해서 body 옵션에 지정해줘야한다.
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Post",
body: "Hello, Post",
userId: 1,
}),
}).then((response) => console.log(response))
.then((data) => console.log(data))
결과
{title: "Post", body: "Hello, Post", userId: 1, id: 101}
PUT 방식은 POST 방식에서 method를 제외하고 차이가 없다.
fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
body: "I am testing!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
결과
{title: "Post", body: "Hello, Post", userId: 1, id: 101}
fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "DELETE",
})
.then((response) => response.json())
.then((data) => console.log(data))
결과
{}