[Express] 라우팅 메소드 put과 delete 이해와 예시
BE/NodeJS 2023. 5. 13.
- app.put()
- app.delete()
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()
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('삭제할 파일이 존재하지 않습니다.');
};
});
'BE > NodeJS' 카테고리의 다른 글
[Node.js] 유효성 검사(Validation), express-validator 사용법 (0) | 2023.05.28 |
---|---|
[Node] findOne 메소드와 조건추가 이해하기 (0) | 2023.05.15 |
[Node] findAll 메소드 활용하여 Database 조회하기 (0) | 2023.05.15 |
[Node] mySQL과 Sequelize를 이용한 데이터베이스 설정 (0) | 2023.05.14 |
[Node.js] readFile과 createReadStream 비교 및 활용방법 (0) | 2023.05.13 |