Node.js - MySQL

저자 수정 기능 구현

강의1

 

 

 

소스코드

변경사항

 

 

 

강의2

 

 

 

소스코드

변경사항 

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 {
      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();
            }
          )
      });
}

 

댓글

댓글 본문
  1. 감자
    22.12.21
  2. 당당
    2022.11.13
  3. 케굴
    2021-12-30
  4. labis98
    20210803 good!!!
  5. 해밀턴
    안녕하세요 질문있어서 질문 남깁니다

    별 표시한곳에 db.query를 한번더 돌리지않고 queryData.id를 이용해서 author 인덱스로 활용했습니다
    이렇게 진행할시 문제가 없을까요?

    문제가 있거나 처리속도가 느리다거나하는 의견있으시면 주시면 감사하겠습니다.


    exports.update= function(request, response){
    var _url = request.url;
    var queryData = url.parse(_url, true).query;
    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/update_process" method="post">
    <p>
    <input type="hidden" name="id" value="${queryData.id}">
    </p>
    <p>
    ★ <input type="text" name="name" placeholder="name" value="${authors[queryData.id-1].name}">
    </p>
    <p>
    ★ <textarea name="profile" placeholder="description">${authors[queryData.id-1].profile}</textarea>
    </p>
    <p>
    <input type="submit" value="update">
    </p>
    </form>
    `
    ,
    `

    `
    );
    response.writeHead(200);
    response.end(html);
    });
    });
    }
  6. hanel_
    21.3.28
  7. chimhyangmoo
    21.03.19
  8. jeisyoon
    2021.03.13 저자 수정기능 - OK
  9. 김지호
    21 01 04
  10. 생활둘기
    2021 1 3
  11. 콜라
    20201022 완료
  12. 암말
    감사합니다!
  13. 준바이
    감사합니다
  14. sukbu
    마리아 10.4로 진행 중
    Error: ER_TRUNCATED_WRONG_VALUE: Truncated incorrect DOUBLE value: '6"'

    querystring 모듈이랑 원인 찾으려고 이것저것 뒤적거려 봤는데 원인을 못찾아서
    [post.name, post.profile, parseInt(post.id)] 로 땜질해서 되긴 하는데.... 석연찮네요 ㅠㅠ
  15. 굼벵이
    완료
  16. Specialist
    수강완료!!!
  17. jo_onc
    맞습니다~ 넘겨 받은 변수의 값과 사용할 변수의 값을 동일하게 맞춰야합니다~
    대화보기
    • DOTOLEE
      69line db.query(`SELECT * FROM author WHERE id=?`,[queryData.id], function(error3,author){
      error3 옆에 author를 authors로 하고
      <input type="text" name="name" value="${author[0].name}" placeholder="name">와
      <textarea name="profile" placeholder="description">${author[0].profile}</textarea>
      value="${author[0].name}" {author[0].profile} 값의 author를 authors로 할 경우
      update 시, 선택한 한 author만 저자 목록에 나옵니다~
      왜 강사님이랑 다를까 해서 고민하다보니 찾았네요 ㅎㅎㅎ
    • 연수아빠
      수강완료!!