이번에는, MySQL 을 이용해서, 웹앱을 제작해볼 것이다.
우선, MySQL 과 연동을 시키기 위해서, 연결 코드를 작성한다.
var mysql = require('mysql');
var conn = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '111111',
port:'3306',
database : 'o2'
});
conn.connect();
해당 코드를 작성했다면, 이제 MySQL 과 연결이 시작되었다.
localhost:3000/topic 으로 접근하면, MySQL에 있는 글들이 목록형태로 나오도록 코드를 작성한다.
app.get(['/topic', '/topic/:id'].function(req,res){
// sql 문에서 id와 title을 가져오면, 해당 데이터에 대한 정보를 가져오기 수월하다.
var sql = "SELECT id, title from topic";
// results 대신, topics 로 대신한다.
conn.query(sql, function(error, topics, fields){
// views_mysql 폴더에 view 를 사용할 것이다.
res.send(res.render('view', {
topics: topics
});
);
};
};
해당 폴더로 세팅을 변경해야하기 때문에, 경로를 수정한다.
app.set('views', './views_mysql');
그리고, view.jade
에서 글 목록 부분을 수정한다.
ul
each topic in topics
li
a(href='/topic/'+topic.id) = topic.title
article
if topic
h2=title
=description
else
h2 Welcome
| This is server side Javascript tuotorial.
글 목록을 눌렀을 때, /topic/1
이런 식의 경로로 접속하기 위해서, topic.title
로 되어있는 링크를 만든다.
topic
이 있다면, title
과 description
을 가져와서 보여주고,