[JS] 동기와 비동기 (4) : fetch

Local Gaji·2023년 5월 20일

JavaScript

목록 보기
10/18

fetch 함수

요청 (Request) 및 응답 (Responce)을 처리하는 함수

fetch(주소, 옵션)

Promise 인스턴스를 반환한다

// 1. then 사용
fetch(주소, 옵션)
  .then(res => res.json())
  .then(json => console.log(json))

// 2. async await 사용
const wrap = async () => {
  const res = await fetch(주소, 옵션)
  const json = await res.json()
  console.log(json)
}
wrap()

fetch 옵션

fetch(주소, {
  method: 'GET',     
  headers: {          
    'Content-Type': 'application/json'
  }, 
  body: JSON.stringify({  
    firstname: 'gaji',
    lastname: 'local' 
  })
 
})
  • headers : 요청에 대한 정보
  • body : 요청에 대한 데이터
    • JSON.stringify : 자바스크립트 데이터를 문자화하여 전송해야한다.

0개의 댓글