2022-07-23
앞서 올린 비동기통신 종류들에 대한 연장선으로 es6에 있는 fetch에 대하여 조금은 사용하기 쉬운 형태의 모듈형태가 있어 간단한게 정리해놓을려고 한다
fetch(url, options)
.then((response) => console.log("response:", response))
.catch((error) => console.log("error:", error));
첫 번 째 인자로는 url로 내가 요청할려는 서버의 주소를 넣어준다
두 번 째 인자로는 옵션객체들을 받게 된다
반환형은 Promise객체형태
fetch()함수는 엄밀히 말하면 브라우저의 window 객체에 소속되어 있기에 window.fetch()로도 사용되기도 한다
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log(data));
대부분 json형태의 데이터를 응답하기에 응답객체는 주로 json()메서드로 한번 풀어준다.json->js 객체로 변환
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "plugnplay",
body: "포스트로 보내기!!!!",
userId: 1,
}),
}).then((response) => console.log(response));
method 옵션으로 rest api 방식 지정
headers 옵션으로 json포맷을 사용을 한다는 것을 알리고
body 옵션에 json포맷으로 직렬화한 데이터 보내기~
단지 DELETE는 보내는 게 없으니 body가 없다
async function post(host, path, body, headers = {}) {
const url = `https://${host}/${path}`;
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
...headers,
},
body: JSON.stringify(body),
};
const res = await fetch(url, options);
const data = await res.json();
if (res.ok) {
return data;
} else {
throw Error(data);
}
}
post("jsonplaceholder.typicode.com", "posts", {
title: "Test",
body: "I am testing!",
userId: 1,
})
.then((data) => console.log(data))
.catch((error) => console.log(error));
asyc/await를 사용하여 비동기 처리로
매번 쓰이는 옵션들에 대하여 중복성을 간단하게 줄일 수 있다!