fetch, fetch API

김종현·2023년 3월 23일
0

API

목록 보기
1/1

Fetch

fetch() 란?
-원격 API를 간편하게 호출할 수 있도록 브라우저에서 제공하는 함수
-자바스크립트를 사용하면 필요할 때 서버에 네트워크 요청을 보내고 새로운 정보를 받
아오는 일을 할 수 있다.
-HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작
할 수 있는 인터페이스를 제공

요청하는 것 : get/post/put/delete
-get : 데이터 받기
-post : 데이터 생성
-put : 데이터 수정
-delete : 데이터 삭제

fetch()

fetch(url, options)
.then((response) => console.log("response:", response))
.catch((error) => console.log("error:", error));

  • url : 접근하고자 하는 URL
    //파라미터로 url만 단독으로 보내면 get 요청만 함.
  • options : 선택 매개변수, method나 header 등을 지정할 수 있음
  • options 에 아무것도 넘기지 않으면 요청은 GET 메서드로 진행 데이터 추가할 때는 POST
  • fetch() 를 호출하면 브라우저는 네트워크 요청을 보내고 promise 가 반환된다.
//예제 1
let result = fetch(serverURL);
result
.fetch(response => {
if(response.ok) {
//요청 성공
}
})
.catch(error => {
// 요청 실패
})
  • 네트워크 요청 성공 시 Promise는 Response 객체를 resolve 한다.
  • 네트워크 요청 실패 시 Promise는 Response 객체를 reject 한다.
//예제 2 - async/await
let url = 'https://api.github.com/repos/javascript-tutorial/ko.javascript.info/com
mits';
let response = await fetch(url);
let commits = await response.json(); // 응답 본문을 읽고 JSON 형태로 파싱함
alert(commits[0].author.login);
  • response.text() : 응답을 읽고 텍스트를 반환
  • response.json() : 응답을 JSON 형태로 파싱
  • response.formData() : 응답을 FormData 객체 형태로 반환
//예제 3 - promise
fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commit
s')
.then(response => response.json())
.then(commits => alert(commits[0].author.login));

fetch API

-http 활용이 가능
-기존 XMLHTTPRequest를 대체하는 HTTP 요청 API
-Promise를 리턴하도록 정의됨
-네트워크 요청 성공 시 Promise는 REsponse 객체를 resolve, 실패시 reject

let result = fetch(serverURL)

result
	.then(response => {
  if(response.ok){
   //요청 성공 .ok는 확인 메서드
  }
})
	.catch(error =>{
  //요청 실패
})

Response 메서드

fetch(serverURL)
	.then(response => {
		response.ok
		response.status
		response.statusText
		response.url
		response.bodyUsed
})

-Response 객체는 결과에 대한 다양한 정보를 담는다.
-.ok : HTTP Status code가 200-299 사이면 true, 그 외 false이다.

  • 요청에 성공해도 200대가 아니면 false가 뜨게 된다.

-.status : HTTP status code를 담는다
-.url : 요청한 url정보를 담는다.

Header 메서드

fetch(serverURL)
	.then(resp => {
  		for (let [k, y] of resp.headers) {
          console.log(k, v)
        }
})

-response.headers : response 객체의 헤더 정보를 얻을 수 있다.

Body 메서드

fetch(serverURL)
	.then(response => {
  		return response.json()
})
	.then(json => {
  		console.log('body : ', json)
})

-response.json() 메서드는 얻어온 body 정보를 json으로 만드는 Promise를 반환한다.

  • 따라서 상기 코드와 같이 then 체인을 통해 한 번더 반환한 promise를 resolve 해야한다.

-promise가 resolve 되면 얻어온 body 정보를 읽는다.
-response.text(), resopnse.blob(), response.formData() 등의 메서드로 다른 형태의 바디를 읽는다.

POST 요청

fetch(serverURL, {
  method: 'post',
  //2)get, post, put, patch, delete 등 메서드 필드로 여러 요청 메서드 활용가능
  headrer: {
    'Content-Type':'application/json;charset=utf-8',
    Authentication: 'mysecret'
  },
  //1)fetch 메서드 옵션 : url 
  //3)header 정보 넣을 수 있음
  body: JSON.stringify(formData)
  //1)fetch 메서드 옵션 : options 
  //3)body 정보 넣을 수 있음
})
	.then(response => {
  		return response.json()
})
	.then(json => {
  console.log('POST 요청 결과:', json)
})

1)fetch(url, options)로 fetch 메서드 옵션을 넣는다.
2)method 필드로 여러 요청 메서드를 활용한다.
3)headers, body 필드를 활용해 서버에 추가 정보를 보낸다.

profile
나는 나의 섬이다.

0개의 댓글