[Express] 라우팅 메소드 put과 delete 이해와 예시

BE/NodeJS 2023. 5. 13.
  • app.put()
  • app.delete()

app.put('경로', 콜백);

 

app.put()

HTTP PUT 요청을 처리하는 메소드이다. PUT요청은 주로 리소스의 전체 업데이트를 위해 사용된다.

 

 

더보기: CRUD 이해하기

router.put('/:id', (req, res) => {
    const userid = req.params.id;
    const body = req.body;
    const index = tweets.findIndex(tweet => tweet.id === userid);
    if (index !== -1) {  // findIndex가 찾지 못 했을 경우 -1을 리턴한다
        tweets[index] = {...tweets[index], ...body}
        res.status(201).json(tweets);
    } else {
        res.status(404);
    }
});

 


 

 

 

app.delete('경로', 콜백);

 

 

 

app.delete()

HTTP DELETE 요청을 처리하며, 리소스를 삭제하는 역할을 한다.

 

router.delete('/:id', (req, res) => {
    const userId = req.params.id;
    const dataIdx = tweets.findIndex(tweet => tweet.id === userId);
    if (dataIdx !== -1) { 
        tweets.splice(dataIdx, 1);
        res.status(204).json(tweets);
    } else {
        res.send('삭제할 파일이 존재하지 않습니다.');
    };
});