생성을 누르면 post를 받아오는 페이지인 create_process 페이지를
만들어 볼 것이다.
여기에서는 fs.writeFile 함수를 sql문의 INSERT 구문으로 변경해주면 된다.
else if (pathname === "/create_process") {
var body = "";
request.on("data", function (data) {
body = body + data;
});
request.on("end", function () {
var post = qs.parse(body);
db.query(`
INSERT INTO topic (title, description, created, author_id)
VALUES(?, ?, NOW(), ?)`,
[post.title, post.description, 1],
function(error, result){
if(error){
throw error;
}
response.writeHead(302, { Location: `/?id=${title}` });
response.end();
});
단지 응답이 성공하면 해당 글로 보내주는 location: 에 담을 것을 테이블의 id가 무엇인지 알아내서 그 페이지로 돌려주어야 한다. 삽입된 행에 대한 id를 가져오는 방법이 무엇인지 알아야한다.
메뉴얼을 보면 result.insertId를 하면 해당 행의 id를 추출할 수 있다고 한다.
최종수정한 코드는 아래와 같다.
else if (pathname === "/create_process") {
var body = "";
request.on("data", function (data) {
body = body + data;
});
request.on("end", function () {
var post = qs.parse(body);
db.query(
`
INSERT INTO topic (title, description, created, author_id)
VALUES(?, ?, NOW(), ?)`,
[post.title, post.description, 1],
function (error, result) {
if (error) {
throw error;
}
response.writeHead(302, { Location: `/?id=${result.insertId}` });
response.end();
}