[JavaScript] fetch 함수 쓰는 법, fetch 함수로 HTTP 요청하는 법

이은진·2021년 3월 12일
23

JavaScript Study

목록 보기
23/24

fetch 함수는 XMLHttpRequest 객체보다 최근에 나온, HTTP 요청 전송 기능을 제공하는 Web API다. 데이터를 받아오기 위해 습관처럼 쓰던 fetch에 대해 정리해보았다.

1. fetch 함수

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(res => console.log(res))

fetch 함수는 HTTP response 객체를 래핑한 Promise 객체를 반환한다. 따라서 프로미스의 후속 처리 메서드인 then을 사용하여 resolve한 객체를 전달받을 수 있다. (물론 catch, finally도 마찬가지)

fetch 함수가 반환한 Promise 객체

/*
Response {
  __proto__: Response {
    type: 'basic',
    url: 'https://jsonplaceholder.typicode.com/posts/1',
    redirected: false,
    status: 200,
    ok: true,
    statusText: '',
    headers: Headers {},
    body: ReadableStream {},
    bodyUsed: false,
    arrayBuffer: ƒ arrayBuffer(),
    blob: ƒ blob(),
    clone: ƒ clone(),
    formData: ƒ formData(),
    json: ƒ json(),
    text: ƒ text(),
    constructor: ƒ Response()
  }
}
*/

fetch 함수로 받은 Response 객체에는 HTTP 응답을 나타내는 프로퍼티들이 있다. 그 중 json() 내장 함수가 있는데, res.json 메서드 사용 시 HTTP 응답 body 텍스트를 JSON 형식으로 바꾼 프로미스를 반환한다(자주 썼던 .then(res ⇒ res.json())의 의미였다).

[MDN] body.json에 대한 설명

2. fetch 함수로 HTTP 요청하기

fetch 함수에는 HTTP 요청을 전송할 URL, HTTP 요청 메서드, HTTP 요청 헤더, 페이로드 등을 설정한 객체를 전달한다.

2.1. GET: 존재하는 자원을 요청

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

→ 단순히 원격 API에 있는 데이터를 가져올 때 쓰임
→ fetch함수는 디폴트로 GET 방식으로 작동하고, 옵션 인자가 필요 없음.

{
  "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"
}

→ 응답(response) 객체는 json() 메서드를 제공하고, 이 메서드를 호출하면 응답(response) 객체로부터 JSON 형태의 데이터를 자바스크립트 객체로 변환하여 얻을 수 있음.

2.2. POST: 새로운 자원 생성 요청

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

→ 폼 등을 사용해서 데이터를 만들어 낼 때, 보내는 데이터의 양이 많거나, 비밀번호 등 개인정보를 보낼 때 POST 메서드 사용
→ 새로운 포스트 생성 위해서는 method 옵션을 POST로 지정해주고, headers 옵션으로 JSON 포맷 사용한다고 알려줘야 함. body 옵션에는 요청 전문을 JSON 포맷으로 넣어줌.
→ headers에서 json 형식임을 알려주지 않으면 서버에서 못 읽는 문제가 (종종?) 생겼음.

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

2.3. PUT: 존재하는 자원 변경 요청

fetch("https://jsonplaceholder.typicode.com/posts", {
  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))

→ API에서 관리하는 데이터의 수정을 위해 PUT 메서드 사용함.
→ method 옵션만 PUT으로 설정한다는 점 빼놓고는 POST 방식과 비슷

2.4. DELETE: 존재하는 자원 삭제 요청

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

→ 보낼 데이터가 없기 때문에 headers, body 옵션이 필요없음

{}
profile
빵굽는 프론트엔드 개발자

1개의 댓글

comment-user-thumbnail
2021년 4월 14일

Fetch 에 대해 검색 하다가 우연히 들렸는데, 내용 정리가 잘 되어 있어서 보기 좋았어요!
감사합니다~~!!

답글 달기