첫번째 인자 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
fetch() 는 디폴트가 get 이고, get은 요청을 받지않아 option이 필요 없다
fetch("url").then((response)=>
console.log(response)
)
==> Response {status:200,...}
==> 성공시 200
fetch("url") .then((response) => response.json()) .then((data) => console.log(data))
==> Response
{ "userId": 1, "id": 1, ... }
method : post
header: json 포멧을 사용한다고 알려줘야 함
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 }
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 }
fetch("url/id번호", { method: "DELETE", }) .then((response) => response.json()) .then((data) => console.log(data))
==> Response
{ }
같은 코드 반복
ex) head에 "Content-Type": "application/json",
따라서, 비동기 함수 작성 (async/await)