프로그래밍/Node.js

Node.js 생활코딩 정리 – 두번째 웹애플리케이션 글 편집 기능 구현

가카리 2016. 11. 27. 21:54
반응형

Node.js 웹애플리케이션 글 편집 기능 구현1

 

 

특정한 topic을 선택후 edit링크를 통해 데이터를 수정한다.

 

먼저 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 server side js.

ul

li

a(href='/topic/add') add

if topic

li

a(href='/topic/'+topic.id+'/edit') edit

 

위와 같이 하면 글을 클릭했을 때 edit 버튼이 추가된다.

 

 

그다음 라우팅을 추가한다.

 

 

app.get(['/topic/:id/edit'], function(req, res){

var sql = 'SELECT id, title FROM topic';//글목록을 보여주기 위한 쿼리문

conn.query(sql, function(err, topics, fields){

var id = req.params.id;//:id값을 가져옴

if(id){//id 있으면 상세보기

var sql = 'SELECT * FROM topic WHERE id=?';

conn.query(sql, [id], function(err, topic, fields){

if(err){//데이터베이스 에러가 있다면

console.log(err);

res.status(500).send('Internal Server Error');

}else{

res.render('edit', {topics:topics, topic:topic[0]});//topic 쿼리문의 데이터 한개만 넘겨줌

}

});

}else{//id값이 없다면 에러출력

console.log('There is no id.');

res.staus(500).send('Internal server error');

}

});

});

 

 

마지막으로 edit화면을 위한 edit.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

form(action='/topic/'+topic.id+'/edit' method='post')

p

input(type='text' name='title' value=topic.title placeholder='title')

p

textarea(name='description' placeholder='description')

=topic.description

p

input(type='text' name='author' value=topic.author placeholder='author')

p

input(type='submit')

ul

li

a(href='/topic/add') add

 

 

 

실행 화면

아직 제출버튼을 눌렀을 때는 구현이 안됬다.

 

 

 

글 편집 기능 구현2

 

app_mysql.js에서 다음을 추가한다.

 

app.post(['/topic/:id/edit'], function(req, res){

var title = req.body.title;

var description = req.body.description;

var author = req.body.author;

var id = req.params.id;

var sql = 'UPDATE topic SET title=?, description=?, author=? WHERE id=?';

conn.query(sql, [title, description, author, id], function(err, result, fields){

if(err){

console.log(err);

res.status(500).send('Internal Server Error');

}else{

//res.send(result);//이걸로 먼저 result값을 보고서 해야한다.

res.redirect('/topic/'+id);//변경 이동 시켜라

}

});

});

 

 

 

실행 화면

edit버튼을 누른 후 form에서 수정 후 제출 버튼을 누르면

 

다음과 같이 수정이 됨을 알 수 있다.

 

출처 : https://opentutorials.org/course/2136

반응형