1. MySQL에 products 테이블 생성 및 데이터 입력
create table products (
id int not null auto_increment primary key,
name varchar(50) not null,
modelnumber varchar(15) not null,
series varchar(30) not null
);
insert into products (name, modelnumber, series) values('Eric', '01123345', 'Artist');
insert into products (name, modelnumber, series) values('Tom', '01098271134', 'Architect');
|
2. 필요 Package 설치
baesunghan:~/Documents/workspace/nodejs/exam_mysql$npm install express && npm install ejs && npm install mysql
express@4.12.3 ../node_modules/express ├── merge-descriptors@1.0.0 ├── utils-merge@1.0.0 ├── cookie-signature@1.0.6 ├── methods@1.1.1 ├── fresh@0.2.4 ├── cookie@0.1.2 ├── escape-html@1.0.1 ├── range-parser@1.0.2 ├── content-type@1.0.1 ├── finalhandler@0.3.4 ├── vary@1.0.0 ├── parseurl@1.3.0 ├── content-disposition@0.5.0 ├── path-to-regexp@0.1.3 ├── depd@1.0.1 ├── qs@2.4.1 ├── on-finished@2.2.1 (ee-first@1.1.0) ├── debug@2.1.3 (ms@0.7.0) ├── etag@1.5.1 (crc@3.2.1) ├── send@0.12.2 (destroy@1.0.3, ms@0.7.0, mime@1.3.4) ├── proxy-addr@1.0.8 (forwarded@0.1.0, ipaddr.js@1.0.1) ├── serve-static@1.9.3 (send@0.12.3) ├── type-is@1.6.2 (media-typer@0.3.0, mime-types@2.0.11) └── accepts@1.2.7 (negotiator@0.5.3, mime-types@2.0.11) ejs@2.3.1 ../node_modules/ejs mysql@2.6.2 ../node_modules/mysql ├── require-all@1.0.0 ├── bignumber.js@2.0.7
└── readable-stream@1.1.13 (isarray@0.0.1, inherits@2.0.1, string_decoder@0.10.31, core-util-is@1.0.1)
baesunghan:~/Documents/workspace/nodejs/exam_mysql$ npm install body-parser
|
3. 리스트 표시를 위한 list.html 작성
<!DOCTYPE html>
<html>
<head>
<title>List Page</title>
</head>
<body>
<h1>List Page</h1>
<a href="/insert">Insert Data</a>
<hr />
<table width="100%" border="1">
<tr>
<th>DELETE</th>
<th>EDIT</th>
<th>ID</th>
<th>Name</th>
<th>Model Number</th>
<th>Series</th>
</tr>
<% data.forEach(function (item, index) { %>
<tr>
<td><a href="/delete/<%= item.id %>">DELETE</a></td>
<td><a href="/edit/<%= item.id %>">EDIT</a></td>
<td><%= item.name %></td>
<td><%= item.modelnumber %></td>
<td><%= item.series %></td>
</tr>
<% }); %>
</table>
</body>
</html>
|
4. 서비스 실행을 위한 app.js 모듈 작성
// 모듈을 추출
var fs = require('fs');
var ejs = require('ejs');
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
// Mysql과 연결
var client = mysql.createConnection ({
user : 'test',
password : 'test',
database : 'test'
});
// 서버 생성
var app = express();
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// 서버 실행
http.createServer(app).listen(18585, function() {
console.log('server running at http://localhost:18585');
});
|
5. 리스트 조회를 위한 app.js 모듈 작성
// router를 수행해서 페이지 분기
// 리스트 조회
app.route('/')
.get(function(req, res, next) {
getList(req,res,next);
})
.post(function(req, res, next) {
getList(req,res,next);
});
function getList(req, res, next) {
// list.html을 읽음
fs.readFile('list.html', 'utf-8', function(error, data){
// mysql 에서 데이터 query
client.query('SELECT * FROM products', function (error, results) {
// 결과 리턴
res.send(ejs.render(data, {
data : results
}));
});
});
};
|
- list.html 작성
<!DOCTYPE html>
<html>
<head>
<title>List Page</title>
</head>
<body>
<h1>List Page</h1>
<a href="/insert">Insert Data</a>
<hr />
<table width="100%" border="1">
<tr>
<th>DELETE</th>
<th>EDIT</th>
<th>ID</th>
<th>Name</th>
<th>Model Number</th>
<th>Series</th>
</tr>
<% data.forEach(function (item, index) { %>
<tr>
<td><a href="/delete/<%= item.id %>">DELETE</a></td>
<td><a href="/edit/<%= item.id %>">EDIT</a></td>
<td><%= item.id %></td>
<td><%= item.name %></td>
<td><%= item.modelnumber %></td>
<td><%= item.series %></td>
</tr>
<% }); %>
</table>
</body>
</html>
|
- list 페이지
2. Insert/update/delete 를 위한 app.js 모듈 작성
app.route('/edit/:id')
.get(function(req, res, next) {
console.log('id : %s', req.param('id'));
fs.readFile('edit.html', 'utf-8', function(error, data){
client.query('SELECT * FROM products WHERE id = ?', [req.param('id')], function(error, result) {
// 응답
res.send(ejs.render(data, { data : result[0]}));
});
});
})
.post(urlencodedParser, function(req, res, next) {
var body = req.body;
// body.id is undefined. Then use req.param('id')
console.log('id : %s, %s', body.id, req.param('id'));
client.query('UPDATE products SET name = ?, modelnumber = ?, series = ? WHERE id = ?',
[body.name, body.modelnumber, body.series, req.param('id')], function() {
res.redirect('/');
});
});
app.route('/insert')
.get(function(req, res, next) {
fs.readFile('insert.html', 'utf-8', function(error, data) {
res.send(data);
})
})
.post(urlencodedParser, function(req, res, next) {
console.log('insert post');
var body = req.body;
console.log('body : ' + req.body.name);
client.query('INSERT INTO products (name, modelnumber, series) VALUES (?, ?, ?)', [
body.name, body.modelnumber, body.series], function() {
res.redirect('/');
});
});
|
- insert.html 작성
<!DOCTYPE html>
<html>
<head>
<title> Insert Page</title>
</head>
<body>
<h1>Insert Page</h1>
<hr />
<form method="post">
<fieldset>
<legend>Insert Data</legend>
<table>
<tr>
<td><label>Name</label></td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td><label>ModelNumber</label></td>
<td><input type="text" name="modelnumber" /></td>
</tr>
<tr>
<td><label>Series</label></td>
<td><input type="text" name="series" /></td>
</tr>
</table>
<input type="submit" />
</fieldset>
</form>
</body>
</html>
|
- edit.html 작성
<!DOCTYPE html>
<html>
<head>
<title> Edit Page</title>
</head>
<body>
<h1>Edit Page</h1>
<hr />
<form method="post">
<fieldset>
<legend>Edit Data</legend>
<table>
<tr>
<td><label>ID</label></td>
<td><input type="text" name="id" value="<%= data.id %>" disabled/></td>
</tr>
<tr>
<td><label>Name</label></td>
<td><input type="text" name="name" value="<%= data.name %>"/></td>
</tr>
<tr>
<td><label>ModelNumber</label></td>
<td><input type="text" name="modelnumber" value="<%= data.modelnumber %>"/></td>
</tr>
<tr>
<td><label>Series</label></td>
<td><input type="text" name="series" value="<%= data.series %>"/></td>
</tr>
</table>
<input type="submit" />
</fieldset>
</form>
</body>
</html>
|
* 참고하는 책에서는 express의 router에 대한 로직을 3.x로 작성되어 서비스 실행시 "app.router" is deprecated오류가 발생함
이 글은 Evernote에서 작성되었습니다. Evernote는 하나의 업무 공간입니다. Evernote를 다운로드하세요. |
댓글 없음:
댓글 쓰기