끄적끄적

HTTP Request 메소드의 종류와 기능 본문

CS

HTTP Request 메소드의 종류와 기능

2024. 7. 17. 23:57

https://res.cloudinary.com/practicaldev/image/fetch/s--9G_NLci7--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1uapyaa2ob49xctta1j7.png

 

 

HTTP 요청은 클라이언트 ↔ 서버 간의 통신을 위한 프로토콜입니다.

프로토콜이란? 통신 시스템 사이에서 데어터 고환을 위해 규정된 규칙과 절차입니다.

HTTP 요청의 구성으로는 Request Line, Headers, Body로 구성됩니다.

Request Line은 메서드, URL, HTTP버전으로 구성됩니다. 

 

메서드의 종류로는 

  - GET : 서버에서 데이터를 요청

  - POST : 서버에서 데이터를 제출

  - PUT : 서버에서 데이터를 업데이트

  - DELETE : 서버에서 데이터를 삭제

  - PATCH : 서버에 데이터를 부분적으로 업데이트 

 

각 메서드의 예시를 보겠습니다.

// GET
fetch('https://test.com/api/data', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));



//POST
fetch('https://test.com/api/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
   ...somedata
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));



//PUT
fetch('https://test.com/api/data/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    ...somedata
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));



//DELETE
fetch('https://test.com/api/data/1', { 
  method: 'DELETE',
  headers: {
    'Content-Type': 'application/json'
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));



//PATCH
fetch('https://test.com/api/data/1', { 
  method: 'PATCH',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
   ...somedata
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

 

 

*멱등성 : 동일한 요청을 여러 번 수행하더라도 결과가 같은 속성

'GET', 'PUT', 'DELETE' 은 여러번 요청을 수행하더라도 멱등한 속성을 갖습니다.

'POST'는 새로운 리소스를 생성하므로 여러번 반복하면 계속 서버 상태가 변경될 수 있으니 멱등하지 않습니다.

'PATCH'는 요청에 따라 다릅니다.

만약 patch의 목적이 기존값을 1씩 증가시는 요청 이라하면 멱등성을 갖지 않고,

username을 newname으로 바꾸는 것 같은 요청은 멱등성을 갖습니다.

 


 

HTTP 응답 상태 코드

- 1xx: 요청이 수신되어 처리중

- 2xx: 요청이 성공적으로 처리

- 3xx: 요청완료를 위해 추가작업이 필요함

- 4xx: 클라이언트 오휴

- 5xx: 서버가 요청 처리 중 오류발생

Comments