JavaScript Fetch API

정의:

Fetch API는 네트워크 요청을 수행하기 위한 인터페이스를 제공합니다. 이는 XMLHttpRequest에 비해 더 유연하고 강력하며, Promise 기반의 구조로 설계되어 있습니다.

기본 사용법:

GET 요청:

가장 기본적인 형태의 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 요청:

POST 요청을 보낼 때는 methodbody 속성을 설정해야 합니다.

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 객체를 반환하며, 이를 통해 여러 메서드와 속성에 액세스할 수 있습니다: