[Restful] REST - 주석 Update

Zero·2023년 3월 13일
0

REST

목록 보기
7/8

PATCH

흔히 업데이트를 요청하는데 쓰이는 것은 PUTPATCH가 있다. PUT은 전체적인 내용을 업데이트 할 때 주로 사용되어 페이로드에 있는 건 무엇이든 요청에 포함할 것이다. 반면 PATCH는 부분적으로 수정이 가능하다.

app.patch('/comments/:id', (req,res) => {
  const {id} = req.params;
  const newComment = req.body.comment;
  const foundComment = comments.find( c => c.id === id);
  foundComment.comment = newComment;
  res.redirect('/comments');
})

--> 기존의 comment 내용이 woof woof woof 였는데, postman을 통해 patch 요청으로 해당 comment의 내용을 수정해주었더니, hello world로 잘 변경된 것을 볼 수 있다.

그렇다면 이제는 폼을 직접 작성하여, comment를 수정하는 작업을 해보자 !



폼을 이용하여 PATCH 요청 수행하기

app.patch('/comments/:id', (req,res) => {
  const {id} = req.params;
  const newComment = req.body.comment;
  const foundComment = comments.find( c => c.id === id);
  foundComment.comment = newComment;
  res.redirect('/comments');
})

app.get('/comments/:id/edit', (req,res)=> {
  const {id} = req.params;
  const comment = comments.find( c => c.id === id);
  res.render('comments/edit', {comment});
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Edit</title>
</head>

<body>
  <h1>Edit</h1>
  <form method="post" action="/comments/<%= comment.id %>?_method=PATCH">
    <textarea name="comment" id="" cols="30" rows="10">
    <%= comment.comment %>
    </textarea>
    <br>
    <button>Save</button>
  </form>
</body>

</html>

edit.ejs 템플릿을 생성하고 위와 같이 작성해주면


다음과 같은 Edit 페이지가 나오게 되고, 해당 textarea 에는 comment의 내용이 삽입되어져 나온다.

이 때 주의할 점이 한 가지 있는데, 브라우저는 get이나 post의 요청밖에 수행하지 못하기 때문에 PATCH요청을 하기 위해서는 별도의 패키지를 하나 사용해야 한다.



method-override

method-override 패키지를 이용해 브라우저가 수행할 수 없는 PUT,DELETE,PATCH 같은 요청을 수행 가능하도록 만들어준다.

설치

npm i method-override
// 선언 및 use 등록
const methodOverride = require('method-override');

app.use(methodOverride('_method'));

해당 패키지를 사용하면

  <form method="post" action="/comments/<%= comment.id %>?_method=PATCH">
    <textarea name="comment" id="" cols="30" rows="10">
    <%= comment.comment %>
    </textarea>
    <br>
    <button>Save</button>
  </form>

해당 폼에서 처럼 post 메소드를 사용하지만, _method=PATCH 를 통해서 사실상 PATCH를 수행하도록 오버라이딩 해준 것이 되는 셈이다.

--> edit 페이지에서 textarea를 이용하여 comment를 수정하였다.

0개의 댓글