반응형
lib/template.js
authorTable:function(authors){
var tag = '<table>';
var i = 0;
while(i < authors.length){
tag += `
<tr>
<td>${authors[i].name}</td>
<td>${authors[i].profile}</td>
<td><a href="/author/update?id=${authors[i].id}">update</a></td>
<td>delete</td>
</tr>
`;
i++;
};
// update에 a태그 붙이고 이동 링크는 author/update?id=author의 id값
tag += '</table>';
return tag;
}
lib/author.js
var db = require('./db');
var template = require('./template.js');
var qs = require('querystring');
var url = require('url');
exports.update = function(request, response){
db.query('SELECT*FROM topic', function(error, topics){
db.query('SELECT*FROM author', function(error2, authors){
var _url = request.url;
var queryData = url.parse(_url, true).query;
db.query('SELECT*FROM author WHERE id=?', [queryData.id], function(error3, author){
// id가 queryData.id값인 author값 가져와 author에 담기
var title = 'Author';
var list = template.list(topics);
var html = template.HTML(title, list,
`
${template.authorTable(authors)}
<style>
table { border-collapse: collapse}
td {border: 1px solid #333; padding: 5px 10px}
</style>
<form action="/author/update_process" method="post">
<input type="hidden" name="id" value="${queryData.id}">
<p><input type="text" name="name" value="${author[0].name}"></p>
<p><textarea name="profile">${author[0].profile}</textarea></p>
<p><input type="submit" value="update"></p>
</form>
`,
``
);
// update클릭 시 /author/update_process로 이동하면서 id값으로 queryDate.id 전달
// name에 선택된 author 이름값 출력
// profile에 선택된 author 프로파일값 출력
response.writeHead(200);
response.end(html);
});
});
});
}
exports.update_process = function(request, response){
var body = '';
request.on('data', function(data){
body += data;
});
request.on('end', function(){
var post = qs.parse(body);
db.query('UPDATE author SET name=?, profile=? WHERE id=?', [post.name, post.profile, post.id], function(error, result){
// 받아온 post값 업데이트
if(error){ throw error; }
response.writeHead(302, {Location: `/author`});
response.end();
});
});
}
반응형
'Dev > Nodejs-mysql' 카테고리의 다른 글
[Nodejs-mysql] 보안의 중요성 (0) | 2020.08.07 |
---|---|
[Nodejs-mysql] 테이블값 삭제하기 (0) | 2020.08.07 |
[Nodejs-mysql] 폼 만들고 모듈 분리하기 (0) | 2020.08.07 |
[Nodejs-mysql] 테이블 만들고 모듈 분리하기 (0) | 2020.08.07 |
[Nodejs-mysql] DB 관련 코드 모듈로 분리하기 (0) | 2020.08.07 |