자바스크립트 fetch()

Jemin·2023년 5월 16일
0

프론트엔드

목록 보기
6/50
post-thumbnail

여러 프로젝트를 진행하면서 API 호출을 할 때 fetch함수나 axios, ajax를 사용했었는데, 사실 어디서 배우거나 학습한적 없이 그냥 검색해서 사용했었던 것 같다.
곧 카카오 브레인 과제 테스트가 있기 때문에 시간을 내서 자세하게 학습해보기로 했다.

참고자료:
자바스크립트의 fetch() 함수로 원격 API 호출하기
Fetch 사용하기 [MDN]
[JavaScript] fetch 함수 쓰는 법, fetch 함수로 HTTP 요청하는 법

fetch 사용법

fetch()함수는 첫 번째 인자로 URL, 두 번째 인자로 옵션 객체를 받고, Promise타입의 객체를 반환한다. 반환된 객체는, API호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error)객체를 reject한다.

fetch(url, options)
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error));

옵션(options)객체에는 HTTP방식(method), HTTP요청 헤더(headers), HTTP요청 전문(body) 등을 설정해줄 수 있다.
응답(response)객체로 부터는 HTTP응답 상태(status), HTTP응답 전문(body) 등을 읽어올 수 있다.

GET 호출

GET요청은 자원을 조회하기 위한 요청이다.
fetch()함수는 기본으로 GET 방식으로 작동하고 GET 방식은 요청 전문을 받지 않기 때문에 옵션 인자가 필요 없다.

fetch("https://jsonplaceholder.typicode.com/posts/1").then((response) =>
  console.log(response)
);

응답 객체를 통해 응답 상태가 200 OK인 것을 알 수 있다.

Response {
  status: 200, 
  ok: true, 
  redirected: false, 
  type: "cors", 
  url: "https://jsonplaceholder.typicode.com/posts/1",}

대부분의 REST API들은 JSON 형태의 데이터를 응답하기 때문에, 응답(response) 객체는 json() 메서드를 제공한다.

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => console.log(data));

이 메서드롤 호출하면, 응답(response) 객체로 부터 JSON 포멧의 응답 전문을 자바스크립트 객체로 변환하여 얻을 수 있다.

{
  "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 호출

POST요청은 새로운 자원을 생성하기 위한 요청이다.
fetch()함수로 POST요청을 보내기 위해서는 method옵션을 POST로 지정해주고, headers옵션을 통해 JSON포멧을 사용한다고 알려줘야 하며, 요청 전문을 JSON포멧으로 직렬화하여 가장 중요한 body옵션에 설정해준다.

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));

응답 객체를 통해 응답 코드가 201 Created인 것을 알 수 있다.

Response {
  type: "cors",
  url: "https://jsonplaceholder.typicode.com/posts", 
  redirected: false, 
  status: 201, 
  ok: true,}

GET 요청과 마찬가지로 응답 객체의 json() 메서드를 호출하면 응답 전문을 객체 형태로 얻을 수 있다.

{
  title: "Test",
  body: "I am testing!",
  userId: 1,
  id: 101
}

PUT, DELETE 호출

GETPOST만큼은 아니지만, 원격 API에서 관리하는 데이터의 수정과 삭제를 위해서 PUTDELETE 방식의 HTTP 호출을 해야할 때가 있다.

PUT요청은 자원의 수정을 위한 요청이다.
PUT방식은 method옵션만 PUT으로 설정한다는 점 빼고는 POST방식과 매우 흡사하다.

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));

DELETE요청을 자원을 삭제하기 위한 요청이다.
DELETE방식에서는 보낼 데이터가 없기 때문에 headers, body 옵션이 필요없다.

profile
꾸준하게

0개의 댓글