9시 24분
저자 기능 추가 ( in 상세 글, 생성 ) 본문
left join을 이용해서 누가 작성한 글인지도 나타내보자.
상세 글 페이지를 나타내는 else 문을 아래와 같이 수정하자.
else{
db.query(`SELECT * FROM topic`, function(error, topics){
if(error) throw error;
db.query(`SELECT * FROM topic left join author on topic.author_id=author.id WHERE topic.id=?`,
[queryData.id],function(error2, topic){
if(error2) throw error2;
var title = topic[0].title;
var description = topic[0].description;
var list = template.list(topics);
var html = template.HTML(title, list,
`<h2>${title}</h2>
${description}
<p>by ${topic[0].name}</p>`,
`<a href="/create">create</a>
<a href="/update?id=${queryData.id}">update</a>
<form action="delete_process" method="post">
<input type="hidden" name="id" value="${queryData.id}">
<input type="submit" value="delete">
</form>`
);
response.writeHead(200);
response.end(html);
});
});
}
이제 글 생성 페이지에서 글 작성 시 저자를 누구로 할지 고를 수 있도록 하자.
< main.js 변경사항 >
} else if(pathname === '/create'){ // 생성
db.query(`SELECT * FROM topic`, function(error, topics){
db.query(`SELECT * FROM author`, function(error2, authors){
var tag = '';
var i = 0;
while(i<authors.length){
tag += `<option value="${authors[i].id}">${authors[i].name}</option>`
i++;
}
var title = 'Create';
var description = 'write description';
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>
`,
`<a href="/create">create</a>`
);
response.writeHead(200);
response.end(html);
});
});
} else if(pathname === '/create_process'){ // 생성 submit
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(), ?)`,
[post.title, post.description, post.author],
function(error, result){
if(error) throw error;
response.writeHead(302, {Location: `/?id=${result.insertId}`});
response.end();
}
);
});
}
< template.js 변경사항>
,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">
${tag}
</select>
`;
}
생활코딩에는 글 수정 시 저자를 바꾸는 기능도 있지만, 나중에 회원가입 기능을 추가하는 것을 고려하여 이 부분은 스킵하장 절대 귀찮아서 그런거 아님 (~ ̄▽ ̄)~
'Javascript > Node.js' 카테고리의 다른 글
저자 관리 기능 구현 - CRUD & SQL injection (0) | 2021.07.06 |
---|---|
코드를 정리정돈 해보자 (0) | 2021.07.05 |
글 생성, 수정, 삭제 기능 구현 (0) | 2021.07.05 |
MySQL 모듈 기본사용법, 홈페이지 구현, 상세보기 구현 (0) | 2021.07.05 |
실습 준비 (0) | 2021.07.05 |