티스토리 뷰

Server/Node.js

[Node.js] PUT; 수정하기

공부하는 승승 2023. 7. 16. 02:57

라이브러리 설치(method-override)

npm install method-override

 

<server.js>

- 해당 파일 상단에 선언

const methodOverride = require('method-override');
app.use(methodOverride('_method'));

 

- PUT을 사용할 폼에 추가

<form action="/edit?_method=PUT" method="POST">
	...
</form>

 

<edit.ejs>

<form action="/edit?_method=PUT" method="POST">
    <div class="form-group">
        <label>오늘의 할일</label>
        <input type="text" value="<%= post._id %>" name="id" style="display: none" /> <!-- 글 id -->
        <input value="<%= post.title %>" type="text" class="form-control" name="title" /> <!-- 수정할 값의 name -->
    </div>
    <div class="form-group">
        <label>날짜</label>
        <input value="<%= post.date %>" type="text" class="form-control" name="date" />
    </div>
    <button type="submit" class="btn btn-outline-secondary">수정</button>
</form>

 

 

<server.js>

/* edit : 수정 */
// 수정페이지 이동
app.get('/edit/:id', function (요청, 응답) {
    db.collection('post').findOne({ _id: parseInt(요청.params.id) }, function (에러, 결과) {
        console.log(결과);
        응답.render('edit.ejs', { post: 결과 });
    });
});

// PUT; 수정하기
app.put('/edit', function (요청, 응답) {
    // updateOne(수정할 것, 수정할 값, 콜백함수)
    db.collection('post').updateOne(
        { _id: parseInt(요청.body.id) },
        { $set: { title: 요청.body.title, date: 요청.body.date } },
        function (에러, 결과) {
            console.log('수정완료');
            응답.redirect('/list');
        }
    );
});
댓글