[JS] Fetch Api

Jay ·2022년 4월 8일
0

1. fetch API

웹에 어떤 리소스를 비동기로 요청하기 위해선 XML, Https request 등을 사용할 수 있지만, Fetch API를 사용하면 이를 좀 더 수월하게 진행할 수 있다.

기본적으로 Promise에 기반하고 있다.

하나의 메소드와 4가지 인터페이스를 가지고 있다.
1) fetch()
2) Headers
3) Response
4) Requests
5) Method

1-1 fetch()

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

ex) .then(res => res.json())
내장 메소드인 .json을 사용

fetch('https://fictiondbs.com')
  .then(res => console.log(res))
  
  /*
Response {
  __proto__: Response {
    type: 'basic',
    url: 'https://fictiondbs.com',
    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()
  }
}
*/

1-2 method

GET, POST, DELETE 등을 선택해서 사용.

만약 지정을 안할 경우 기본값은 “GET”이 된다. 그리고 소문자로 지정해도 자동으로 대문자로 Uppercase된다.

fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })

1-3 headers

Headers 객체는 HTTP Header와 대응되는 객체이다.

fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    })
    
// headers의 prototype
append: function append()
delete: function delete()
entries: function entries()
forEach: function forEach()
get: function get()
getAll: function getAll()
has: function has()
keys: function keys()
set: function set()
values: function values()
constructor: function Headers()
Symbol(Symbol.iterator): function ()
Symbol(Symbol.toStringTag): "Headers"

Headrs를 설정하지 않으면 API에서 메소드로 접근이 불가능해진다. headaers에서 application.json 같이 설정을 해줘야 인코딩을 통해 메소드 접근이 가능해진다.

`api/fictions/create.tsx`

1) console.log(req.body)

// {id: ~, emial:~,~ }

2) console.log(req.body.id)

// undefined

1-4 request

Request는 HTTP 요청을 통해 자원을 가져오는 인터페이스이다.
Request는 URL, Header, body가 필요하다. 그리고 Request에 대한 mode 제한과 certificate 관련 설정도 추가할 수 있다.

Request 객체의 첫번째 인자는 호출한 Path가 들어가고, 두번째 인자에는 Request에 대한 정보가 들어가는데,

method, headers body, mode, cache, credentials, redirect, referrer, integrity 가 들어간다.

1-5 response

fetch()는 Promise를 리턴하는데 Promise에서 값을 추출하면 Response를 얻을 수 있다. 마찬가지로 자세한 사항은 문서를 확인하자

1) body

body는 HTTP Requests에 실을 데이터로, 여러가지 타입을 넣을 수 있다.

typedef (Blob or BufferSource or FormData or URLSearchParams or ReadableStream or USVString)

Blob도 보낼 수 있는 부분을 보면 파일전송까지 모두 고려한것으로 볼 수 있고, FormData와 URLSearchParams도 넣을 수 있도록 모두 고려되어 있다.

profile
Jay입니다.

0개의 댓글