[Javascript] fetch
Updated:
- Fetch API는 요청/응답과 같은 HTTP 파이프라인을 조작하고 접근할 수 있는 인터페이스를 제공
fetch()
라는 메서드를 제공, 쉽고 논리적인 방식으로 리소스를 네트워크 통해 비동기 fetch 가능XMLHttpRequest
의 기능과 유사하지만, *service workers와 같은 다른 기술에서 쉽게 사용되어질 수 있는 더 나은 대안- jquery의 ajax와는 조금 다름
fetch()
가 리턴하는 promise는 HTTP error status(ex. HTTP 404 or 500) 를 reject 하지 않음- 대신 promise는 응답으로 false값을 세팅한
ok
프로퍼티를 resolve함 (응답 범위가 200대가 아니면) - credentials init option을 세팅하지 않으면, cross-origin cookies를 보내지 않음
Usage
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
- 제일 간단한 사용법은 하나의 argument 값(fetch 하고 싶은 리소스의 경로)만 받음
- response를 포함하는 promise를 return
- 단순 HTTP response이기 때문에 JSON를 추출하기 위해
json()
메서드 사용
Supplying request options
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
사용성 개선 - async/await 모듈화
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));
ref :
Using Fetch(MDN)
ServiceWorker 이모저모 이야기
fetch() 함수로 API 호출하기
Leave a comment