자바스크립트에서 네트워크 요청을 보내는 주요 방법은 XMLHttpRequest 객체와 fetch 함수이다. 이 두 가지 방법을 통해 클라이언트는 서버와 데이터를 주고받을 수 있다.
XMLHttpRequest 객체는 오래된 방식의 네트워크 요청 방법으로, 브라우저가 서버와 상호 작용할 수 있게 한다. 주로 AJAX 요청에 사용된다.
fetch 함수는 최신 방식의 네트워크 요청 방법으로, 더 간단하고 직관적인 API를 제공한다.
fetch("~")
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
fetch(url): 지정된 URL로 네트워크 요청을 보낸다..then(response => response.json()): 응답을 JSON 형식으로 파싱한다..then(data => console.log(data)): 파싱된 데이터를 처리한다..catch(error => console.error("Error:", error)): 요청 중 발생한 에러를 처리한다.fetch 함수는 두 번째 인수로 옵션 객체를 받을 수 있다. 이를 통해 HTTP 메서드, 헤더, 바디 등을 설정할 수 있다.
fetch("~", {
method: "POST", // HTTP 메서드
headers: {
"Content-Type": "application/json" // 요청 헤더
},
body: JSON.stringify({
title: "새 작업",
completed: false
}) // 요청 본문
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));
method: HTTP 메서드를 설정합니다. (예: GET, POST, PUT, DELETE)headers: 요청 헤더를 설정합니다. (예: Content-Type)body: 요청 본문을 설정합니다. 주로 POST나 PUT 요청에서 사용됩니다.
내용이 너무 없는데;