이번 포스트에서는 HTTP 메서드에 대해 알아보겠습니다.
먼저, HTTP란 무엇인지 알아야 합니다. HTTP는 Hypertext Transfer Protocol의 약자로, 웹상에서 클라이언트와 서버가 통신(데이터를 주고 받는 행위)하기 위해 사용하는 일종의 규약입니다. HTTP는 현재 인터넷에서 가장 널리 사용되는 프로토콜 중 하나이며, 요청(request)와 응답(response)을 이용하여 데이터를 주고 받습니다. 클라이언트는 요청을 보내고, 서버는 이에 응답하며 통신이 이루어 집니다.
HTTP 요청은 일반적으로 URL을 통해 지정된 리소스에 대한 액션(조회, 추가, 수정, 삭제 등)과 데이터를 포함합니다. 예를 들어, 브라우저에서 웹 페이지를 요청하는 경우 GET 메서드를 사용하고, 서버에 데이터를 전송하는 경우 POST 메서드를 사용합니다.
HTTP 응답은 요청에 대한 결과를 나타내며, 상태 코드(status code), 헤더, 본문 등의 정보를 포함합니다. 상태 코드는 요청의 성공 또는 실패를 나타내며, 200 OK
, 404 Not Found
, 500 Internal Server Error
등이 있습니다.
HTTP 메서드는 클라이언트가 서버에 요청을 보내는 방식을 의미합니다. 아래 기본적인 4개의 메서드들의 특징과, fetch함수를 통해 각 메서드를 이용해 서버에 요청을 보내는 예시까지 하나씩 알아보겠습니다.
fetch('https://example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
const postData = { name: 'John Doe', email: 'johndoe@example.com' };
fetch('https://example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(postData),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
const putData = { name: 'Jane Doe', email: 'janedoe@example.com' };
fetch('https://example.com/data/123', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(putData),
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
fetch('https://example.com/data/123', {
method: 'DELETE',
})
.then(response => {
if (response.ok) {
console.log('Resource deleted successfully.');
} else {
console.error('Error deleting resource.');
}
})
.catch(error => console.error(error));
위에서 알아본 4가지의 기본 메서드 외에도 여러 메서드들이 있습니다. 다만 기본 메서드들에 비해 사용되는 빈도가 현저히 낮습니다. 간단히만 알아보겠습니다.