본문 바로가기
HTTP

[HTTP] Delete 요청을 보내면 응답을 못 받을까?

by 2D3 2022. 11. 3.
728x90

 

 

Contents

     

    문제점

    어느 때와 같이 CRUD 작업을 하고 있었는데, 프론트엔드에서 Delete 요청을 할 때 Id 값을 받아야 된다고 했다.

     

    @DeleteMapping("/{comment-id}")
    public ResponseEntity deleteComment(
            @PathVariable("comment-id") @Positive long commentId) {
    
        commentService.deleteComment(commentId);
    
        return new ResponseEntity<>(new CommentDeleteDto(commentId), HttpStatus.NO_CONTENT);
    
    }

    Controller에 반환값으로 commentId를 받을 수 있게 내용을 수정하고

    @Getter
    public class CommentDeleteDto {
    
        private long commentId;
    
        public CommentDeleteDto(long commentId) {
            this.commentId = commentId;
        }
    
    }

    DeleteDto를 만들어서 CommentId를 저장했다.

     

    그 결과...

    정상적으로 만들어진 답변이 싹 지워졌다... id도 남기지 않고..

    반환으로 ID를 주는 게 맞는데 왜 전부 다 지워버렸을까??

    그 답은 HttpStatus에 있다.

     

    해결 방법

    @DeleteMapping("/{comment-id}")
    public ResponseEntity deleteComment(
            @PathVariable("comment-id") @Positive long commentId) {
    
        commentService.deleteComment(commentId);
    
        return new ResponseEntity<>(new CommentDeleteDto(commentId), HttpStatus.OK);
    
    }

    다른 코드는 전부 동일한데 HttpStatus.OK로 바꾸자 원하는 대로 응답을 받을 수 있었다.

     

    왜 HttpStatus에 따라 응답이 다를까?

    Http 상태코드 2XX 성공적인 응답
    200 OK 요청 성공. 데이터는 요청에 따른 응답으로 반환
    204 NO CONTENT Response Body가 존재하지 않음 (헤더는 사용가능)

    204 코드는 정말 말 그대로 요청한 것을 삭제하여 Body가 필요없을 때 사용하는 것이기 때문에, 아무리 로직이 완벽하더라도 응답값을 받을 수 없는 것이었다.

     

    728x90

    댓글