fetch 함수
fetch는 클라이언트에서 서버요청을 할 수 있는 함수이다. Web API 함수.
(Web API는 자바스크립트 내장함수. 즉, 외부 라이브러리가 아니다)
Ajax를 구현할 수 있는 여러가지 기술 중, 최신 기술이 fetch 함수이다.
< Ajax >
- Asynchronous Javascript And Xml(비동기식 자바스크립트와 XML)
- 클라이언트와 서버간에 XML 데이터를 주고받는 기술,
- 자바스크립트를 통해 클라이언트에서 서버에 데이터를 요청하고 그 결과를 받을 수 있는 기술
실무에서 axios를 많이 쓰는데 fetch도 왠만한 것은 다 처리할 수 있다고 한다.
fetch() 함수는 엄밀히 말해, 브라우저의 window 객체에 소속되어 있기 때문에 window.fetch()로 사용되기도 한다.
fetch 함수의 기본 형식을 알아보자.
// arrow 함수형
fetch(url, options)
.then((response) => console.log("response:", response))
.catch((error) => console.log("error:", error));
// 함수 선언형
fetch(url, options)
.then(function(response) {
console.log("response:", response);
})
.catch(function(error) {
console.log("error:", error));
})
fetch() 함수는 첫번째 인자로 URL, 두번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환한다. 반환된 객체는, API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error) 객체를 reject한다.
fetch('서버주소')는 웹 브라우저에게 '이 서버주소로 요청해줘'라는 의미이다. 뒤에 .then은 '요청이 성공적으로 끝나면 이걸 해줘'라는 뜻이고 .catch는 '요청이 제대로 처리되지 않으면 이걸 해줘'라는 뜻이다.
fetch 함수의 http요청에 대해 알아보자.
1. GET (존재하는 자원을 요청)
- 단순히 원격 API에 있는 데이터를 가져올 때 쓰임
- fetch함수는 디폴트로 GET 방식으로 작동하고, 옵션 인자가 필요 없음.
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) =>
console.log(response)
);
결과값은 아래와 같다. Response 객체를 받고 응답상태는 200 인 것을 알 수 있다.
status는 HTTP 상태코드를 말하며 ok는 boolean 값으로 상태코드가 200~299 사이일 때 true이다.
Response {status: 200, ok: true, redirected: false, type: "cors",
url: "https://jsonplaceholder.typicode.com/posts/1", …}
대부분의 REST API들은 JSON 형태의 데이터를 응답하기 때문에, 응답(response) 객체는 json() 메서드를 제공한다.
json() 메서드를 호출하면 응답(response) 객체를 json형태로 파싱한다.
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"
}
2. POST (새로운 자원 생성 요청)
- form 등을 사용해서 데이터를 만들어 낼 때, 보내는 데이터의 양이 많거나, 비밀번호 등 개인정보를 보낼 때 POST 메서드 사용
- 새로운 포스트 생성을 위해서는 method 옵션을 POST로 지정해주고, headers 옵션으로 JSON 포맷을 사용한다고 알려줘야 한다.
- body 옵션에는 요청 전문을 JSON 포맷으로 넣어준다(JSON.stringfy() 함수에 객체를 인자로 전달하여 JSON 문자열 형태로 변환).
- headers에서 json 형식임을 알려주지 않으면 서버에서 못 읽는 문제가 생길 수 있다.
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
body: "I am testing!",
userId: 1,
}),
}).then((response) => console.log(response));
결과값은 아래와 같다. Response 객체를 받고 응답상태는 201 인 것을 알 수 있다.
Response {type: "cors", url: "https://jsonplaceholder.typicode.com/posts", redirected: false, status: 201, ok: true, …}
동일하게 json() 메서드를 호출해보자.
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "laugh",
body: "I am laughing!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data));
결과는 아래와 같이 자바스크립트 객체로 나타난다.
{title: "laugh", body: "I am laughing!", userId: 1, id: 101}
3. PUT (존재하는 자원 변경 요청)
- API에서 관리하는 데이터의 수정을 위해 PUT 메서드를 사용한다.
- method 옵션만 PUT으로 설정한다는 점 빼놓고는 POST 방식과 비슷하다.
fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "smile",
body: "I am smiling!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data));
결과값은 아래와 같다.
{title: "smile", body: "I am smiling!", userId: 1, id: 1}
4. DELETE (존재하는 자원 삭제 요청)
DELETE 방식에서는 보낼 데이터가 없기 때문에, headers와 body 옵션이 필요가 없다.
fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "DELETE",
})
.then((response) => response.json())
.then((data) => console.log(data));
결과는 아래와 같다.
{}