프로그래밍에서 작업 처리하는 방식
정의 : JS에서 제공하는 내장 통신 함수
역할 : HTTP 요청을 보내고 응답을 비동기적으로 처리
사용법
then 이용한 체인 형식, 실행 순서 보장 안됨() => {
fetch(url, option)
.then(response => response.json())
.then(data => { })
.catch(error => { })
}async/await 이용한 동기 형식, 권장, 실행 순서 보장됨async () => {
try {
const response = await fetch(url, option);
const data = await response.json();
} catch(error) {
console.log(error);
}
}옵션 설명
url : Spring 프로젝트 내 통신할 controller의 @XXXMapping에서 정의된 URL url?param1=${value1}¶m2=${value2}option : { method: "GET" }{ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }then(응답객체 => 응답객체.json()) : 응답 객체를 JSON 타입으로 변환 .json() 불가능then(변환된 객체 => { 실행문 }) : 통신 응답 결과 처리catch(에러객체 => { 실행문 }) : 통신 에러 발생 처리