
이번에는 원격 API을 간편하게 호출할 수 있도록 브라우저에서 제공하는 fetch() 함수에 대해서 이야기해보고자 한다.
목차
1.Fetch
2.사용 방법
Fetch
원래 원격 API 호출하면 제일 먼저 떠오르는 것이 request, axios, jquery와 같은 라이브러리이다. 브라우저에서 fetch()을 지원하기 전까지는 클라이언트 단에서 직접 http요청을 하고 응답받는 게 상당히 복잡해서 이러한 라이브러리 사용이 합리적이었지만 이제는 브라우저에 내장되어 있는 fetch() 함수를 이용한다면 대부분의 경우 충분하게 API을 호출할 수 있다.
사용 방법
fetch() 함수는 첫 번째 인자로 URL, 두 번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환한다. 옵션 객체에는 HTTP 방식(method), HTTP 요청헤더(headers), HTTP 요청전문(body) 등을 읽어 올 수 있다.
포트 8000으로 백엔드 서버를 열어 뒀다고 가정한 다음, http method별 fetch() 함수의 사용방법은 아래와 같다.
// GET
fetch("http://127.0.0.1:8000/api/posts/")
.then((response) => response.json())
.then((data) => console.log(data));
// POST
fetch("http://127.0.0.1:8000/api/posts/", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
content: "I am testing!",
user: 1,
}),
}).then((response) => console.log(response));
// PATCH
fetch("http://127.0.0.1:8000/api/posts/1/", {
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
}),
}).then((response) => console.log(response));
// DELETE
fetch("http://127.0.0.1:8000/api/posts/1/", {
method: "DELETE",
}).then((response) => console.log(response));
각 요청이 성공하면 다음과 같은 응답 코드를 받을 수 있다.
- get 요청 성공 시 : 200 OK
- post 요청 성공 시 : 201 Created
- patch 요청 성공 시 : 200 OK
- delete 요청 성공 시 : 204
이를 매번 작성하면 번거로우니 객체로 저장하여 간편하게 사용하는 방법도 있다.
const request = {
get(url) {
return fetch(url);
},
post(url, payload) {
return fetch(url, {
method: 'POST',
headers: { 'content-Type': 'application/json' },
body: JSON.stringify(payload)
});
},
patch(url, payload) {
return fetch(url, {
method: 'PATCH',
headers: { 'content-Type': 'application/json' },
body: JSON.stringify(payload)
});
},
put(url, payload) {
return fetch(url, {
method: 'PUT',
headers: { 'content-Type': 'application/json' },
body: JSON.stringify(payload)
});
},
delete(url) {
return fetch(url, {method: 'DELETE'});
}
};
// POST 예시
request.post('https://jsonplaceholder.typicode.com/posts', {
id: 1,
userId:1,
title: "프공",
body: "프론트공부"
})
.then(res => res.json())
.then(data => console.log(data));
// DELETE 예시
request.delete("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log(data));
'Programing Language > Javascript' 카테고리의 다른 글
npm과 yarn (0) | 2023.09.02 |
---|---|
[Javascript] default export와 named export (0) | 2023.03.29 |
[Javascript] Date 객체 사용하기 (0) | 2023.03.22 |
[Javascript] setTimeout()과 setInterval() 함수 (0) | 2023.03.21 |
[Javascript] Local Storage 다루기 (0) | 2023.03.21 |