Fetch API

비지·2023년 10월 4일
0

엘트

목록 보기
2/16

Fetch API

let result fetch(serverURL)

result
	.then(response => {
	if (response.ok) {
    	//요청 성공.
    }
  })
  .catch(error => {
  	   //요청 실패
  })
  • 기존 XMLHTTPRequest를 대체하는 HTTP 요청 API
  • ES6에 추가된 Promise를 리턴하도록 정의됨
  • 네트워크 요청 성공 시, Promise는 Response 객체를 resolve 한다.
  • 네트워크 요청 실패 시, Promise는 에러를 reject 한다.

Response

fetch(serverURL)
	.then(response => {
    	response.ok
        response.status
        response.statusText
        response.url
        response.bodyUsed
    })
  • Response 객체는 결과에 다양한 정보를 담는다.
  • response.ok는 HTTP Status code가 200-299 사이면 true, 그 외 false이다.
  • response.status는 HTTP status code를 담는다.
  • response.url은 요청한 URL 정보를 담는다.

Body 메서드

fetch(serverURL)
	.then(response => {
    	return response.json()
    })
    .then(json => {
    	console.log('body : ',
     json)
    })
  • response.json() 메서드는 얻어온 body 정보를 json으로 만드는 Promise를 반환한다.
  • Promise가 resolve 되면 얻어온 body 정보를 읽는다.
  • response.text(), response.blob(), response.formData() 등의 메서드로 다른 형태의 바디를 읽는다.

POST 요청

fecth(serverURL, {
	method: 'post',
    headers: {
    	'Content-Type':
    'application/json;cjarset=utf-8',
    	Authentication: 'mysecret'
     },
     body: JSON.stringify(formData)
   })
   	.then(response => {
    	return response.json()
      })
    .then(json => {
    	console.log('POST 요청 결과:', json)
     })
  • fecth(url, options)로, fetch 메서드 옵션을 넣는다.
  • method 필드로 여러 요청 메서드를 활용한다.
  • headers, body 필드를 활용해 서버에 추가 정보를 보낸다.
profile
나를 위한 업그레이드 아자아자

0개의 댓글