반응형
[생활코딩] MySQL join을 이용해서 글생성 구현
데이터 Select의 option으로 만들기
if(pathname === '/create'){
db.query('SELECT*FROM topic', function(error, topics){
db.query('SELECT*FROM author', function(error2, authors){
// author값 가져와서 authors에 담기
var tag = '';
var i = 0;
while(i < authors.length){
tag = tag + `<option value="${authors[i].id}">${authors[i].name}</option>`
i++;
}
// authors값 반복문으로 option 만들어 tag에 담기
// value값으로 authors[i].id 저장
var title = 'WEB - create';
var list = template.list(topics);
var html = template.HTML(title, list, `
<form action="/create_process" method="post">
<p><input type="text" name="title" placeholder="title"></p>
<p><textarea name="description" placeholder="description"></textarea></p>
<p>
<select name="author">
<option selected disabled hidden>Select</option>
${tag}
</select>
</p>
<p>
<input type="submit">
</p>
</form>
`, '');
// select안에 option인 tag 넣기
// submit시 select의 name인 author의 값으로 선택된 옵션 value값 넘김
response.writeHead(200);
response.end(html);
});
});
}
객체지향을 위해 tag를 template.js로 옮겨서 사용하기
template.js
module.exports = {
HTML:function(title, list, body, control){...},
list:function(topics){...},
authorSelect:function(authors){
var tag = '';
var i = 0;
while(i < authors.length){
tag += `<option value="${authors[i].id}">${authors[i].name}</option>`
i++;
}
return `
<select name="author">
<option selected disabled hidden>Select</option>
${tag}
</select>
`
}
}
main.js
if(pathname === '/create'){
db.query('SELECT*FROM topic', function(error, topics){
db.query('SELECT*FROM author', function(error2, authors){
var title = 'WEB - create';
var list = template.list(topics);
var html = template.HTML(title, list, `
<form action="/create_process" method="post">
<p><input type="text" name="title" placeholder="title"></p>
<p><textarea name="description" placeholder="description"></textarea></p>
<p>${template.authorSelect(authors)}</p>
<p>
<input type="submit">
</p>
</form>
`, '');
// template에서 authorSelect불러오고 전달할 인자에는 authors 넣기
response.writeHead(200);
response.end(html);
});
});
}
선택된 option값 저장하기
if(pathname === '/create_process'){
var body = '';
request.on('data', function(data){
body = body + data;
});
request.on('end', function(){
var post = qs.parse(body);
var title = post.title;
var description = post.description;
db.query('INSERT INTO topic (title, description, created, author_id) VALUES (?, ?, NOW(), ?)',[title, description, post.author], function(error, result){
// author_id에 post.author값 넣기
if(error){ throw error; }
response.writeHead(302, {Location: `/?id=${result.insertId}`});
response.end();
});
});
}
반응형
'Dev > Nodejs-mysql' 카테고리의 다른 글
[Nodejs-mysql] DB 관련 코드 모듈로 분리하기 (0) | 2020.08.07 |
---|---|
[Nodejs-mysql] Select값 수정하기 (0) | 2020.08.07 |
[Nodejs-mysql] Join된 테이블에서 값 가져오기 (0) | 2020.08.06 |
[Nodejs-mysql] 데이터 수정/삭제하기 (0) | 2020.08.06 |
[Nodejs-mysql] 데이터 넣고 출력하기 (0) | 2020.08.05 |