fetch()로 API호출

Soly; 독특하게·2020년 12월 2일
0

JavaScript

목록 보기
2/7
post-thumbnail

첫번째 인자 URL
두번째 인자 객체
⇒ promise타입의 객체 반환

성공 ) response 객체를 resolve
실패 ) error객체를 reject

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

option 객체 ) method, headers, body
response 객체 ) status, headers, body

Get

  • 정보를 가져옴

fetch() 는 디폴트가 get 이고, get은 요청을 받지않아 option이 필요 없다

fetch("url").then((response)=>
	console.log(response)
)
==> Response {status:200,...} 
==> 성공시 200

EX)

fetch("url")
	.then((response) => response.json())
	.then((data) => console.log(data))

==> Response

{
	"userId": 1,
	"id": 1,
	...
}

Post

  • 데이터 생성

method : post
header: json 포멧을 사용한다고 알려줘야 함

EX)

fetch("url",{
	method: "POST",
	headers: {
		"Content-Type": "application/json",
	},
	data: JSON.stringfy({
		title: "Test",
		body: "testing",
		userId: 0,
	}),
})
	.then((response) => response.json())
	.then((data) => console.log(data))

==> Response

{
	"id": 1
}

PUT

  • 데이터 수정

method : put

fetch("url", {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  data: JSON.stringfy({
		title: "Test",
		body: "testing",
		userId: 0,
	}),
})
  .then((response) => response.json())
  .then((data) => console.log(data))

==> Response

{
	"id": 1
}

Delete

  • 데이터 삭제
  • 보낼 데이터가 없어 data옵션 필요없음
fetch("url/id번호", {
  method: "DELETE",
})
  .then((response) => response.json())
  .then((data) => console.log(data))

==> Response

{
}

보완

  • 같은 코드 반복
    ex) head에 "Content-Type": "application/json",

  • 따라서, 비동기 함수 작성 (async/await)

profile
협업을 즐겨하는 목표지향적인, Front-End 개발자입니다.

0개의 댓글