데브코스 TIL-day15 fetch api &회고

조주영·2021년 8월 20일
0

데브코스-TIL

목록 보기
15/34

fetch api 사용하기

fetch는 http error가 발생하더라도
reject 되지않는다
네트워크 에러나 요청이 완료되지 못한 경우에만
reject 된다
그러므로 서버 요청 중 에러가 생겼을 경우에도 then으로 떨어지므로, response의 status code나 ok를 체크해주는 것이 좋습니다.

fetch('https://kdt.cho.codes/undefined.-api')
	.then(res=>res.json(){
     if(
    .then(data=> {
          console.log(data)
          })
    .catch(e=>{
      	document.querySelector('body).innerHTML=e.message
//에러가 난다
//response바디를 json으로 바꾸려고 할때, 요청이 실패했는데도 reject하지 않는다.

그래서 res.ok를 통해 요런식으로 류 검수과정이 필요하다

fetch('https://kdt.cho.codes/undefined.-api')
	.then(res=>res.json(){
     if(res.ok){
  		return res.json()
		}
	throw new Error('요청이 처리되지 못함')
    .then(data=> {
          console.log(data)
          })
    .catch(e=>{
      	document.querySelector('body).innerHTML=e.message
fetch('http//kdt/roto/code/todos')
	.then(res =>{
    	return res.json()
        })
    .then(todo=>{
       //todos 조회완료
        console.log(todos)
     })

fetch의 두 번째 인자로 옵션을 줄 수 있는데,
첫번째 인자는 GET요청이다.
두번째는 요청을 하면서 옵션을 줄수있다
클라이언트 서버 분리가되어있다면, 인증토크같은 것은 header에 넣는다 라던지,
post같은경우에는 request 바디에다가 새로운 프로덕트를 추가하는 요청을 하고싶으면,
바디에다가 json스트링 형태로 추가할 상품을 넣어 서버에서 바디를 json으로 파싱해서 작업을한다.
요런식

const headers = new Headers()

headers.append('X-auth-token', 'TOKEN')
fetch('https://kdt.roto.codes/product',{
  	method:'POST'
  	headers,
  	body:JSON.stringfy(product)
})

끝! 오늘은 포스팅이 비교적짧은데, 다음포스팅인 회고에서 이어집니다!

profile
꾸준히 성장하기

0개의 댓글