Fetch API

HOONEY·2021년 12월 28일
0

Javascript

목록 보기
1/8
post-thumbnail

$.ajax 대신 쓰기

- fetch란

  1. ES6 문법으로 비동기로 서버와 통신 방법이다.
  2. return값으로 Promise를 받는다. -> 사용 시 return response.json() 처리 필요

- 문법

  • 기본 문법
fetch(url).then(function(response) {
  // Code ...
}).catch(function(error) {
  // Error
  console.error(error);
});;
  • 옵션 세팅 가능
fetch(url, {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
}).then(function(response) {
  // Code ...
});

요청(Request)시 설정할 수 있는 옵션으로는 아래와 같다.

  • method - GET, POST, PUT, DELETE
  • headers - header 옵션
  • body - parameter 등
  • mode - cors 등의 값을 설정 (cors, no-cors, same-origin)
  • cache - 캐쉬 사용 여부 (no-cache, reload, force-cache, only-if-cached)
  • credentials - 자격 증명을 위한 옵션 설정(include, same-origin, omit) (Default. same-origin)

$.ajax를 자주 사용하면서 항상 사용하던 옵션들(url, type, data, dataType, contentType)만 사용해봤는데, cache, credentials 같은 옵션들을 공부해봐야겠다.

jQuery를 안쓰는 추세이기 때문에 앞으로 vanilla js만 사용할 때 사용해봐야겠다.

profile
기록하는 블로그

0개의 댓글