HTTP 요청 메서드 설정
이 단계에서는 XMLHttpRequest 를 사용하여 HTTP 요청 메서드를 구성하는 방법을 배웁니다. ajax-demo.html 파일을 업데이트하여 다양한 유형의 HTTP 요청을 설정하는 방법을 시연합니다.
WebIDE 에서 ~/project/ajax-demo.html 파일을 열고 스크립트 섹션을 수정합니다.
<!doctype html>
<html>
<head>
<title>HTTP Request Methods</title>
</head>
<body>
<h1>AJAX Request Methods</h1>
<button id="getButton">GET Request</button>
<button id="postButton">POST Request</button>
<div id="result"></div>
<script>
// GET Request Configuration
document
.getElementById("getButton")
.addEventListener("click", function () {
var xhr = new XMLHttpRequest();
// Configure GET request
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
// Set request headers
xhr.setRequestHeader("Content-Type", "application/json");
// Log request details
console.log("GET Request Configured");
// Send the request
xhr.send();
});
// POST Request Configuration
document
.getElementById("postButton")
.addEventListener("click", function () {
var xhr = new XMLHttpRequest();
// Configure POST request
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts", true);
// Set request headers
xhr.setRequestHeader("Content-Type", "application/json");
// Prepare data to send
var data = JSON.stringify({
title: "foo",
body: "bar",
userId: 1
});
// Log request details
console.log("POST Request Configured");
// Send the request with data
xhr.send(data);
});
</script>
</body>
</html>
HTTP 요청 메서드
가장 일반적인 HTTP 요청 메서드는 다음과 같습니다.
- GET: 서버에서 데이터 검색
- POST: 서버에서 처리할 데이터 제출
- PUT: 기존 데이터 업데이트
- DELETE: 데이터 삭제
요청 구성을 위한 주요 메서드
-
open(method, url, async):
method: HTTP 메서드 (GET, POST 등)
url: 서버 엔드포인트
async: 비동기 요청에 대한 부울 값 (일반적으로 true)
-
setRequestHeader(): 요청 헤더 설정
-
send(): 요청 전송 (선택적 데이터 포함)
예시 출력
버튼을 클릭하면 다음과 같은 콘솔 로그가 표시됩니다.
GET Request Configured
POST Request Configured