ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2023 - 07 - 01 Node.js Fetch 메서드 (GET, POST, PUT, DELETE)
    Today I Learned/TIL 07 2023. 7. 3. 16:34

    Fetch API

     

    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 응답 헤더(headers), HTTP 응답 전문(body) 등을 읽어올 수 있다. 참고로 fetch() 함수는 엄밀히 말해, 브라우저의 window 객체에 소속되어 있기 때문에 window.fetch()로 사용되기도 한다.

     

    Fetch방식의 API (https://jsonplaceholder.typicode.com/ 예제)

    fetch() 함수는 디폴트로 GET 방식으로 작동하고 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", …}
    
    응답 객체를 통해 응답 상태가 200 OK인 것을 금방 알 수 있다.

     

    이 메서드를 호출하면, 응답(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 호출

    원격 API에서 관리하고 있는 데이터를 생성해야 한다면 요청 전문을 포함할 수 있는 POST 방식의 HTTP 통신이 필요하다.

    동일한 API를 대상으로 이번에는 새로운 포스팅를 생성하기 위해서 fetch() 함수를 사용해보자. 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));
    Response {type: "cors", url: "https://jsonplaceholder.typicode.com/posts", 
    redirected: false, status: 201, ok: true, …}

     

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

    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) => response.json())
      .then((data) => console.log(data));
      
      
      //
      {title: "Test", body: "I am testing!", userId: 1, id: 101}

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

     

    PUT, DELETE 호출

    격 API에서 관리하는 데이터의 수정과 삭제를 위해서 PUT과 DELETE 방식의 HTTP 호출을 해야할 때가 있다.

    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));
      
      //
      {title: "Test", body: "I am testing!", userId: 1, id: 1}

     

    DELETE 방식에서는 보낼 데이터가 없기 때문에, headers body 옵션이 필요가 없다.

     

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

     

     

    예제.

    async function post(host, path, body, headers = {}) {
      const url = `https://${host}/${path}`;
      const options = {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          ...headers,
        },
        body: JSON.stringify(body),
      };
      const res = await fetch(url, options);
      const data = await res.json();
      if (res.ok) {
        return data;
      } else {
        throw Error(data);
      }
    }
    
    post("jsonplaceholder.typicode.com", "posts", {
      title: "Test",
      body: "I am testing!",
      userId: 1,
    })
      .then((data) => console.log(data))
      .catch((error) => console.log(error));

     

    MDN문

    https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

    댓글

Designed by Tistory.