이번 파트에서는, ①기존에 있는 데이터를 가져오고, ② 기존에 있는 데이터를 수정하는 "편집" 기능을 다뤄볼 것이다.
우선, 데이터를 먼저 가져와야하기 때문에, mysql
에 있는 데이터를 가져오는 데 쓰였던 코드를 복사해서 수정한다.
app.get(['/topic/:id/edit'], function(req, res) {
var sql = "SELECT id,title FROM topic";
conn.query(sql, function(error, topics, fields) {
// id 값이 반드시 존재해있어야한다.
var id = req.params.id;
if (id) {
var sql = "SELECT * FROM topic WHERE id=?"
conn.query(sql, [id], function(error, topic, fields) {
if (error) {
console.log(error);
res.status(500).send('Internal Server Error');
} else {
res.render('edit', {
topics: topics,
topic: topic[0]
});
}
});
} else {
// id 가 없을 때 에러를 찍어준다.
console.log('There is no id');
res.status(500).send('Internal Server Error');
}
});
}
);
edit.jade
파일로 보여주도록 한다.→ edit.jade
파일을 만들어야한다. (add.jade
파일과 유사한 형태이기 때문에, add.jade 파일을 복사해서 수정한다.)
→ view.jade
수정
(view.jade
)
doctype html
html
head
meta(charset='utf-8')
body
h1
a(href='/topic') Server Side Javascript
ul
each topic in topics
li
a(href='/topic/'+topic.id)= topic.title
article
if topic
h2=topic.title
=topic.description
div= 'by '+topic.author
else
h2 Welcome
| This is sever side Javascript tutorial.
ul
li
a(href='/topic/add') add
if topic
li
a(href='/topic/'+topic.id+'/edit') edit
div
태그 대신, ul
과 li
태그를 활용한다.'/topic' +topic.id+'/edit'
로 이동하도록 한다.edit
버튼이 나오도록 if
구문을 삽입한다.(edit.jade
)