fetch에는 일반적인 오브젝트로 request와 response가 포함되어 있다. 또한 CORS나 HTTP 오리진 헤더의 행동에 관련한 개념에 대해서도 정의되어 있다. fetch()를 불러들이는 경우, 취득할 리소스를 반드시 인수로 지정하지 않으면 안된다. fetch()는 promise객체를 반환. 리퀘스트가 성공하든 실패하든 해당 리퀘스트 통신에 대한 response객체가 취득된다. fetch()의 두번째 인수는 초기화에 사용되는 객체를 정의하고 있다.
fetch('http://example.com/movies.json')
.then((response) => response.json())
.then((data) => console.log(data));
async function postData(url = '',data={}){
const response = await fetch(url,{
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type':
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringfy(data),
});
return response.json();
}
postData('https://example.com/answer',{answer:42}).then((data) =>{
console.log(data);
});
fetch('flowers.jpg')
.then((response) => {
if (!response.ok) {
throw new Error('네트워크 응답이 올바르지 않습니다.');
}
return response.blob();
})
.then((myBlob) => {
myImage.src = URL.createObjectURL(myBlob);
})
.catch((error) => {
console.error('fetch에 문제가 있었습니다.', error);
});