<script>
let response = await fetch(url);
if(response.ok)
{
let json = await response.json();
} else
{
alert("에러발생")
}
</script>
fetch('https://api.example.com/nonexistent')
.then(response => {
if (!response.ok) {
throw new Error('HTTP error! Status: ' + response.status);
}
return response.json(); // JSON 데이터 추출
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Fetch error: ', error); // HTTP 요청 실패 또는 네트워크 오류 처리
});
// GET 요청을 보낼 URL
const url = 'https://api.example.com/data';
// 헤더 설정을 포함한 fetch 요청
fetch(url, {
method: 'GET', // 요청 메서드
headers: {
'Content-Type': 'application/json', // 원하는 헤더를 여기에 추가
'Authorization': 'Bearer YourAccessToken', // 인증 토큰을 추가할 수도 있음
// 다른 원하는 헤더도 추가 가능
},
})
.then(response => {
if (!response.ok) {
throw new Error('HTTP error! Status: ' + response.status);
}
return response.json(); // JSON 데이터 추출
})
.then(data => {
console.log(data); // 성공한 경우 데이터 출력
})
.catch(error => {
console.error('Fetch error: ', error); // 에러 처리
});
JSON.stringify() 함수를 사용하여 수행JSON.parse() 함수를 사용하여 수행직렬화(Serialization)는 데이터나 객체를 특정 형식(일반적으로 바이트 스트림 또는 문자열)으로 변환하는 과정을 의미 변환된 데이터는 저장, 전송 또는 공유될 수 있다, 나중에 역직렬화를 통해 원래 형식으로 복원될 수 있다.
목적 : 데이터 저장, 데이터 전송, 상태저장 및 복원, 데이터 교환