Node.js - MySQL

MySQL join을 이용해서 글생성 구현

수업소개

MySQL의 join을 이용해서 Node.js 웹앱의 글 생성 기능을 구현하는 방법을 살펴보겠습니다. 

 

 

 

강의

 

 

 

소스코드

변경사항

main.js

var http = require('http');
var fs = require('fs');
var url = require('url');
var qs = require('querystring');
var template = require('./lib/template.js');
var path = require('path');
var sanitizeHtml = require('sanitize-html');
var mysql = require('mysql');
var db = mysql.createConnection({
  host:'localhost',
  user:'root',
  password:'111111',
  database:'opentutorials'
});
db.connect();


var app = http.createServer(function(request,response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    var pathname = url.parse(_url, true).pathname;
    if(pathname === '/'){
      if(queryData.id === undefined){
        db.query(`SELECT * FROM topic`, function(error,topics){
          var title = 'Welcome';
          var description = 'Hello, Node.js';
          var list = template.list(topics);
          var html = template.HTML(title, list,
            `<h2>${title}</h2>${description}`,
            `<a href="/create">create</a>`
          );
          response.writeHead(200);
          response.end(html);
        });
      } 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;
           }
           console.log(topic);
          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);
         })
      });
      }
    } else if(pathname === '/create'){
      db.query(`SELECT * FROM topic`, function(error,topics){
        db.query('SELECT * FROM author', function(error2, authors){
          var title = '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>
            `,
            `<a href="/create">create</a>`
          );
          response.writeHead(200);
          response.end(html);
        });
      });
    } 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, post.author], 
            function(error, result){
              if(error){
                throw error;
              }
              response.writeHead(302, {Location: `/?id=${result.insertId}`});
              response.end();
            }
          )
      });
    } else if(pathname === '/update'){
      db.query('SELECT * FROM topic', function(error, topics){
        if(error){
          throw error;
        }
        db.query(`SELECT * FROM topic WHERE id=?`,[queryData.id], function(error2, topic){
          if(error2){
            throw error2;
          }
          var list = template.list(topics);
          var html = template.HTML(topic[0].title, list,
            `
            <form action="/update_process" method="post">
              <input type="hidden" name="id" value="${topic[0].id}">
              <p><input type="text" name="title" placeholder="title" value="${topic[0].title}"></p>
              <p>
                <textarea name="description" placeholder="description">${topic[0].description}</textarea>
              </p>
              <p>
                <input type="submit">
              </p>
            </form>
            `,
            `<a href="/create">create</a> <a href="/update?id=${topic[0].id}">update</a>`
          );
          response.writeHead(200);
          response.end(html);
        });
      });
    } else if(pathname === '/update_process'){
      var body = '';
      request.on('data', function(data){
          body = body + data;
      });
      request.on('end', function(){
          var post = qs.parse(body);
          db.query('UPDATE topic SET title=?, description=?, author_id=1 WHERE id=?', [post.title, post.description, post.id], function(error, result){
            response.writeHead(302, {Location: `/?id=${post.id}`});
            response.end();
          })
      });
    } else if(pathname === '/delete_process'){
      var body = '';
      request.on('data', function(data){
          body = body + data;
      });
      request.on('end', function(){
          var post = qs.parse(body);
          db.query('DELETE FROM topic WHERE id = ?', [post.id], function(error, result){
            if(error){
              throw error;
            }
            response.writeHead(302, {Location: `/`});
            response.end();
          });
      });
    } else {
      response.writeHead(404);
      response.end('Not found');
    }
});
app.listen(3000);

template.js

module.exports = {
  HTML:function(title, list, body, control){
    return `
    <!doctype html>
    <html>
    <head>
      <title>WEB1 - ${title}</title>
      <meta charset="utf-8">
    </head>
    <body>
      <h1><a href="/">WEB</a></h1>
      ${list}
      ${control}
      ${body}
    </body>
    </html>
    `;
  },list:function(topics){
    var list = '<ul>';
    var i = 0;
    while(i < topics.length){
      list = list + `<li><a href="/?id=${topics[i].id}">${topics[i].title}</a></li>`;
      i = i + 1;
    }
    list = list+'</ul>';
    return list;
  },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>
    `
  }
}

 

댓글

댓글 본문
  1. 글을 생성하는데 null 값만 저장되는데 방법이 없을까요?

    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 inventory (goods_code, goods_name, color, count, price)
    VALUES(?,?,?,?,?)` ,
    [post.goods_code, post.goods_name, post.color, post.count, post.price],
    function(error, result){
    if(error){
    throw error;
    }
    response.writeHead(302, {Location: `/?id=${result.insertId}`});
    response.end();
    }
    )

    });
    }

    제가 따로 DB만들어서 하고있습니다.
  2. 감자
    22.12.20
  3. 당당
    2022.11.11
  4. toonfac
    220715 오전 11시 52분 완료
  5. 존레논아부지
    굳~!!! 대만족!!
  6. 화려하게간다
    아니 나는 왜 뭘 만들어도 다 저자가 egoing인거죠???ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ
  7. synodic
    template.js return에 세미콜론 안써도 되나요?
  8. 케굴
    2021-12-29
  9. HyunseoLee
    20210811 ㄹㅇ 진짜 너무 재밌어서 이고잉님 강의 다보는중
  10. labis98
    20210801 명강의 입니다.
  11. hanel_
    21.3.24
  12. chimhyangmoo
    21.03.17
  13. jeisyoon
    2021.03.11 MySQL Joint 글 생성 구현 - OK
  14. 김지호
    21 01 03
  15. 생활둘기
    2021 1 3
  16. 콜라
    20201021 완료
  17. Jonghwo Lee
    완료
  18. 가톨릭대 컴공
    완료
  19. 김보미
    오 감사합니다
  20. 소종원
    전체 코드와 에러가 없어서 확실하게는 모르겠지만, 입력한 글이 DB에 입력되었다면, Location의 주소값이 잘못된것일수도 있습니다. 새로 작성한 글의 id를 DB에서 확인해보시고, 에러가 나오는 페이지의 주소값 맨 뒤에 숫자, 즉 id값이 일치하는지 확인을 해보세요. db와 다른 값이 주소에 출력된다면 Location: `/?id=${results.insertId}` 이렇게 작성된 값이 제대로 써있는지 확인을해보세요
    대화보기
    • 준바이
      감사합니다
    • 김철새
      감사합니다
    • Dea No
      질문이 있습니다.

      글생성 버튼을 누르면 화면에 에러가 뜨고요
      다시 접속해서 들어가보면 글생성과 저자는 잘 나오고 있습니다.

      TypeError: Cannot read property 'description' of undefined
      at Query.<anonymous> (C:\Users\___\Desktop\nodejs\main.js:62:40)

      라는 로그가 뜨고

      저기 62 줄은

      var title = topic[0].title;

      이렇게 되어 있는데 대체 모가 잘못되었는지 모르겠네용.. ㅜㅜ
    • 강다리
      재밌네요
    • 굼벵이
      완료
    • leesj020925@naver.com
      아 죄송합니다 create 부분에서는 author_id 를 가져올 필요가 없었네요 ㅎㅎ
      대화보기
      • leesj020925@naver.com
        궁금한 점이 있어서 질문올립니다.
        else if(pathname === '/create') 내부에 form 을 보면 template.authorSelect(authors) 부분이 있는데요
        template.js 의 authorSelect 는 파라미터를 두개를 받는데 이부분에서는 인자로 authors 하나만 주게 돼있습니다.
        이렇게 되면 template.js 에서 author_id(두번째 파라미터) 는 어디서 가져오게 되는건가요?
      • jo_onc
        수강완료~
      • 연수아빠
        수강완료!!
      버전 관리
      egoing
      현재 버전
      선택 버전
      graphittie 자세히 보기