안전한 메서드와 HEAD 메서드의 사용

kakasoo·2021년 3월 7일
4
post-thumbnail

저번에 이어서 메서드에 대해서 설명하고자 한다.

안전한 메서드

9.1.1 Safe Methods
Implementors should be aware that the software represents the user in
their interactions over the Internet, and should be careful to allow
the user to be aware of any actions they might take which may have an
unexpected significance to themselves or others.
In particular, the convention has been established that the GET and
HEAD methods SHOULD NOT have the significance of taking an action
other than retrieval. These methods ought to be considered "safe".
This allows user agents to represent other methods, such as POST, PUT
and DELETE, in a special way, so that the user is made aware of the
fact that a possibly unsafe action is being requested.
Naturally, it is not possible to ensure that the server does not generate side-effects as a result of performing a GET request; in fact, some dynamic resources consider that a feature. The important distinction here is that the user did not request the side-effects, so therefore cannot be held accountable for them.

당연히 GET 요청의 결과로 서버가 부작용을 초래하지 않을 거라는 것은 보장할 수 없습니다. 몇몇 자원은 이것을 기능으로 간주하기도 하고요. 중요한 것은, 이러한 구별은, 유저들이 일부러 부작용을 초래한 것이 아닐 뿐더러, 유저들에게 책임을 물을 수 없다는 것을 의미합니다

각 메서드는 전적으로 개발자가 어떻게 만드냐에 달려 있다. 따라서 위에 적혀있는 것과 같이, 서버가 부작용을 초래하지 않을 거라는 보장은 할 수 없다. 이는 어느 웹 서버도 마찬가지일 것이다. 그러나, 그렇다고 해서 우리가 API를 만들 때에 규칙을 준수할 필요가 없다는 의미는 아니다. 우리는 여전히 RESTful한 의미에 맞게 서버를 만들어야 할 거고, 그 중에서도 안전한 메서드는 안전한 메서드의 의미에 맞게 만들어야 한다.

가령 GET 메서드는 조회를 위한 메서드이다. 일반적으로 조회가 서버의 리소스를 변경시키는 일은 없기 때문에, 사용자는 당연히 자신의 행위가 서버에 피해를 끼칠 거라고 걱정하지 않을 것이다. 이런 상황에서 웹 서버는 사용자에게 책임을 물을 수 없다는 것을 의미한다.

HEAD

This response is primarily intended to allow input for actions to take place without causing a change to the user agent's active document view, although any new or updated metainformation SHOULD be applied to the document currently in the user agent's active view.

이 응답은 기본적으로 사용자 에이전트의 활성 문서보기를 변경하지 않고 수행 할 작업에 대한 입력을 허용하기위한 것입니다. 그러나 새롭거나 업데이트 된 메타 정보가 현재 사용자 에이전트의 활성보기에있는 문서에 적용되어야합니다.

9.4 HEAD
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
The response to a HEAD request MAY be cacheable in the sense that the
information contained in the response MAY be used to update a previously
cached entity from that resource. If the new field values indicate that the
cached entity differs from the current entity (as would be indicated by a
change in Content-Length, Content-MD5, ETag or Last-Modified), then the
cache MUST treat the cache entry as stale.

RFC 2616 Fielding, et al.

HEAD 메서드는 서버가 응답에서 메시지 본문을 반환하면 안된다는 걸 제외하면 GET 메서드와 똑같습니다. HEAD 요청 시 응답의 HTTP 헤더에 포함된 메타 정보는 GET 요청에 대한 응답으로 전송된 정보와 동일해야 합니다. 이 메소드는 엔티티 바디 자체를 전송하지 않고 요청이 암시하는 엔티티에 대한 메타 정보를 얻는 데에 사용할 수 있습니다. 이 방법은 유효성, 접근성 및 최근 수정에 대해 하이퍼 텍스트 링크를 테스트 하는 데에 자주 사용됩니다.

  • 속도를 비교해봤을 때, HEAD와 GET의 성능 차이는 거의 없었다.
  • HEAD가 Content-Length를 포함하고 있는 한, GET과 마찬가지로 body를 조회할 필요가 있기 때문에, 최종적으로 body를 보내지 않을 뿐이므로 성능 차이를 기대하기는 어렵다.
  • 단, 보내야 하는 resource의 크기가 크거나, 또는 캐시 된 데이터가 최신의 것인지 확인하기 위함이라면 HEAD 메서드를 쓰는 것이 효율적이다.
    • 그러나 빈번하게 정보가 업데이트되는 경우라면 HEAD 메서드를 쓰는 것은 오히려 독이 될 수 있다.
  • 몇몇 개발자는 HEAD와 GET을 두고 성능을 비교하는 것 자체가 무의미한 비교라고 말한다.

HEAD의 사용

static async isAdmin(req, res, next) {
    try {
      const user = req.user;
      const [result] = await model.findAllWhere(user.ID);
      if (result) {
        return res.sendStatus(200);
      }
      return res.sendStatus(400);
    } catch (error) {
      console.error(error);
      return res.sendStatus(401);
    }
}
  • 내가 찾아본 글들에 의하면, HEAD 메서드는 True OR False로 나타낼 수 있는 정보를 위해 사용하는 게 좋다고 한다.
    • 위 코드는 user의 ID를 통해서 그 유저가 admin인지 체크하는, 내가 임의로 만든 함수이다.
  • 이 경우 express 에서는 send 함수보다는 sendStatus 함수로, body가 없다는 것을 명시해야 한다. ( 그렇지 않아도 동작은 하지만, console 창에 수많은 log를 확인하게 될 것이다. )
  • 꼭 저렇게 200, 400으로 분기할 필요 없이, 헤더만으로 소통할 수 있는 다양한 경우에 사용이 가능할 것이다.
  • 로그인 정보가 부족한 경우, 로그인이 잘못된 경우, 클라이언트 측 에러, 서버 측 에러 등 다양하게 사용 가능하다.
profile
자바스크립트를 좋아하는 "백엔드" 개발자

0개의 댓글