[JS] fetch 함수

zzincode·2024년 7월 5일
0

JavaScript

목록 보기
18/24
post-thumbnail

Fetch 함수

: HTTP 요청 전송 기능을 제공하는 클라이언트 사이드 Web API
자바스크립트를 사용해 서버와 쉽게 상호작용할 수 있게 해주는 도구
XMLHttpRequest객체보다 사용법이 간단 & Promise 지원

HTTP 요청을 전송할 URL과 HTTP 요청 메서드, HTTP 요청 헤더, 페이로드 등을 설정한 객체를 전달

const promise = fetch(url [,options])

fetch 함수 사용법

1. URL에 HTTP 요청

→ fetch 함수는 Promise 반환

2. fetch 함수가 반환한 promise가 resolve될 때 실행

→ response.json()메서드는 또 다른 promise 반환(JSON 형태로 파싱된 데이터를 포함)

3. response.json()메서드가 반환한 프로미스가 resolve될 때 실행

→ JSON 형태로 파싱된 데이터 출력

fetch('https://jsonplaceholder.typicode.com/todos/1') //HTTP 요청을 보내고 프로미스를 반환
.then(response => response.json()) //첫 번째 프로미스가 resolve되면, 응답을 JSON으로 파싱
.then(json=>console.log(json));//JSON으로 파싱된 데이터를 콘솔에 출력

적용시키기

//HTTP 요청(fetch함수에 첫번째 인수 HTTP요청을 전송한 URL, 두번째 인수 HTTP 요청 메서드, HTTP 요청 헤더, 페이로드 등을 설정한 객체 전달)
const request = {
  get(url){
    return fetch(url);
  },
  post(url, payload){
    return fetch(url, {
      method : 'POST',
      header : {'content-Type' : 'application/json'},
      body : JSON.stringify(payload)
    });
  },
  patch(url, payload){
    return fetch(url, {
      method : 'PATCH',
      headers : {'content-Type': 'application/json'},
      body: JSON.stringify(payload)
    });
  },
  delete(url){
    return fetch(url, {method : 'DELETE'})
  }
}

//GET 요청
request.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then (todos => console.log(todos))
.catch(err=> console.error(err))

//POST 요청
request.post('https://jsonplaceholder.typicode.com/todos', {
  userId : 1,
  title : 'Javascript',
  compeleted : false,
}).then(response => response.json())
.then (todos => console.log(todos))
.catch(err=> console.error(err))

//PATCH 요청
request.patch('https://jsonplaceholder.typicode.com/todos/1', {
  compeleted : true,
}).then(response => response.json())
.then (todos => console.log(todos))
.catch(err=> console.error(err))

//DELTE 요청
request.delete('https://jsonplaceholder.typicode.com/todos/1', {
}).then(response => response.json())
.then (todos => console.log(todos))
.catch(err=> console.error(err))

0개의 댓글