Node.js - MySQL

저자 삭제 기능 구현

강의

 

 

 

소스코드

main.js

var http = require('http');
var url = require('url');
var topic = require('./lib/topic');
var author = require('./lib/author');

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){
        topic.home(request, response);
      } else {
        topic.page(request, response);
      }
    } else if(pathname === '/create'){
      topic.create(request, response);
    } else if(pathname === '/create_process'){
      topic.create_process(request, response);
    } else if(pathname === '/update'){
      topic.update(request, response);
    } else if(pathname === '/update_process'){
      topic.update_process(request, response);
    } else if(pathname === '/delete_process'){
      topic.delete_process(request, response);
    } else if(pathname === '/author'){
      author.home(request, response);
    } else if(pathname === '/author/create_process'){
      author.create_process(request, response);
    } else if(pathname === '/author/update'){
      author.update(request, response);
    } else if(pathname === '/author/update_process'){
      author.update_process(request, response);
    } else if(pathname === '/author/delete_process'){
      author.delete_process(request, response);
    } else {
      response.writeHead(404);
      response.end('Not found');
    }
});
app.listen(3000); 

 

lib/author.js


var db = require('./db');
var template = require('./template.js');
var qs = require('querystring');
var url = require('url');

exports.home = function(request, response){
    db.query(`SELECT * FROM topic`, function(error,topics){
        db.query(`SELECT * FROM author`, function(error2,authors){
            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 black;
                }
            </style>
            <form action="/author/create_process" method="post">
                <p>
                    <input type="text" name="name" placeholder="name">
                </p>
                <p>
                    <textarea name="profile" placeholder="description"></textarea>
                </p>
                <p>
                    <input type="submit"  value="create">
                </p>
            </form>
            `,
            ``
            );
            response.writeHead(200);
            response.end(html);
        });
    });
}

exports.create_process = function(request, response){
    var body = '';
      request.on('data', function(data){
          body = body + data;
      });
      request.on('end', function(){
          var post = qs.parse(body);
          db.query(`
            INSERT INTO author (name, profile) 
              VALUES(?, ?)`,
            [post.name, post.profile], 
            function(error, result){
              if(error){
                throw error;
              }
              response.writeHead(302, {Location: `/author`});
              response.end();
            }
          )
      });
}

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){
                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 black;
                    }
                </style>
                <form action="/author/update_process" method="post">
                    <p>
                        <input type="hidden" name="id" value="${queryData.id}">
                    </p>
                    <p>
                        <input type="text" name="name" value="${author[0].name}" placeholder="name">
                    </p>
                    <p>
                        <textarea name="profile" placeholder="description">${author[0].profile}</textarea>
                    </p>
                    <p>
                        <input type="submit" value="update">
                    </p>
                </form>
                `,
                ``
                );
                response.writeHead(200);
                response.end(html);
            });
            
        });
    });
}

exports.update_process = function(request, response){
    var body = '';
      request.on('data', function(data){
          body = 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){
              if(error){
                throw error;
              }
              response.writeHead(302, {Location: `/author`});
              response.end();
            }
          )
      });
}

exports.delete_process = function(request, response){
    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 author_id=?`,
            [post.id], 
            function(error1, result1){
                if(error1){
                    throw error1;
                }
                db.query(`
                    DELETE FROM author WHERE id=?`,
                    [post.id], 
                    function(error2, result2){
                        if(error2){
                            throw error2;
                        }
                        response.writeHead(302, {Location: `/author`});
                        response.end();
                    }
                )
            }
        );
      });
}

 

댓글

댓글 본문
  1. 감자
    22.12.21
  2. 당당
    2022.11.14
  3. 대포123
    22.10.30 삭제기능 완료
  4. 케굴
    2021-12-30
  5. labis98
    20210803 good!!!
  6. 해밀턴
    질문 있습니다 제가 아래에 별표 처놓은곳이 서로 바뀌면 문제되는 부분이있나요
    서로 바꿔도 오류가 나지않아서 궁금해서 여쭤봅니다

    아시는분 댓글 많이 남겨주세요

    exports.delete_process =function(request,response){
    //console.log("author_delete_process");
    var body = '';
    request.on('data', function(data){
    body = body + data;
    });
    request.on('end', function(){
    var post = qs.parse(body);
    //console.log(post.id);
    ★ db.query('DELETE FROM topic WHERE author_id = ?', [post.id], function(error1, result1){
    if(error1){
    throw error1;
    }
    ★ db.query('DELETE FROM author WHERE id = ?', [post.id], function(error, result){
    if(error){
    throw error;
    }
    response.writeHead(302, {Location: `/author`});
    response.end();
    });
    });
    });
    }
  7. 이중원
    "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1', '2', '3', '4', '5''' at line 1"

    똑같이 코드를 작성했는데 이런 에러가 나오네요... 해결 방법 아시는 분 계신가요?
  8. hanel_
    21.3.28
  9. chimhyangmoo
    21.03.19
  10. jeisyoon
    2021.03.13 저자 삭제기능 - OK
  11. 김지호
    21 01 04
  12. 생활둘기
    2021 1 3
  13. 콜라
    20201022 완료
  14. error를 error1과 error2로 구분해야하는 이유가 있나요? 코드 흐름대로 진행되면 error 두 개가 동시에 발생하는 경우는 없을테니까 그냥 error로 다 처리해도 괜찮을 것 같다는 생각이 드는데...
  15. 암말
    감사합니다!
  16. 준바이
    감사합니다
  17. 김철새
    author_id 를 쓰는 이유가 있었군요..
  18. 강다리
    이제 영상을 안보고도 구현이 가능하네요
    강의 감사합니다.
  19. 굼벵이
    완료
  20. 코베
    update id 넣는 부분만 보고 나머진 혼자 처리 했어요 감사합니다~!
  21. jo_onc
    CRUD!
    강의 감사합니다!
  22. 누누
    강의를 안보고 그냥 혼자서 구현을 했더니, 선생님의 코드와 차이가 많이 나버렸네요...
    그래서 부랴부랴 author 모듈도 만들고, url도 조금더 깔끔하게 다듬고 오는 길입니다ㅠㅠ
    아무튼 좋은강의 감사합니다!
  23. 연수아빠
    수강완료!!
버전 관리
egoing
현재 버전
선택 버전
graphittie 자세히 보기