
클라이언트에서 서버로 비동기통신을 하기 위해 사용하는 API
네트워크 통신을 포함한 리소스 취득을 위한 인터페이스 정의
Ajax의 방식중 하나
fetch('url', {
Request 설정 옵션
})
.then('함수')
.catch('에러 작업');
GET, POST, PUT, DELETE ...Content-type: application/jsonJSON.stringify(data)fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json'
// 데이터를 json 형태로 보내겠다.
},
body: JSON.stringify(data)
// 전달한 데이터를 json문자열로 변환
});
fetch(url) // fetch는 promise를 반환
.then((response) => response.json())//Object화 시켜줌
.then((data) => console.log(data))
response 객체가 제공하는 json() 메소드를 호출하면 응response 객체로부터 JSON 형태의 데이터를 JS 객체로 변환하여 얻을 수 있다.
fetch 함수의 디폴트는 GET 방식으로 옵션 인자가 필요 없다.
fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((data) => console.log(data))
fetch(url, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((data) => console.log(data))
fetch(url, {
method: "DELETE",
})
.then((response) => response.json())
.then((data) => console.log(data))