Fetch API는 네트워크 요청을 수행하기 위한 인터페이스를 제공합니다. 이는 XMLHttpRequest에 비해 더 유연하고 강력하며, Promise 기반의 구조로 설계되어 있습니다.
가장 기본적인 형태의 Fetch 요청은 URL을 지정하여 리소스를 가져오는 것입니다.
fetch('<https://api.example.com/data>')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // or response.text() for text data
})
.then(data => {
console.log(data);
})
.catch(error => {
console.log('There was a problem with the fetch operation:', error.message);
});
POST 요청을 보낼 때는 method와 body 속성을 설정해야 합니다.
const data = { username: 'example' };
fetch('<https://api.example.com/user>', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Fetch API는 response 객체를 반환하며, 이를 통해 여러 메서드와 속성에 액세스할 수 있습니다:
response.text(): 응답을 텍스트로 반환합니다.response.json(): 응답을 JSON으로 파싱하여 반환합니다.response.blob(): 응답을 Blob 객체로 반환합니다 (예: 이미지 파일).response.headers: 응답 헤더를 가져옵니다.