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;
          }
          db.query('SELECT * FROM author', function(error2, authors){
            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>
                  ${template.authorSelect(authors, topic[0].author_id)}
                </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=? WHERE id=?', [post.title, post.description, post.author, 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, author_id){
    var tag = '';
    var i = 0;
    while(i < authors.length){
      var selected = '';
      if(authors[i].id === author_id) {
        selected = ' selected';
      }
      tag += `<option value="${authors[i].id}"${selected}>${authors[i].name}</option>`;
      i++;
    }
    return `
      <select name="author">
        ${tag}
      </select>
    `
  }
}

 

댓글

댓글 본문
작성자
비밀번호
  1. http://www.yeezy-500.us.com
    http://www.redbottom-shoes.us.com
    http://www.cheap-airjordans.us.com
    http://www.filashoes.us.org
    http://www.nike-hyperdunk.us.com
    http://www.yeezyboost350v2.org.uk
    http://www.curry4.net
    http://www.yeezysshoes.us.com
    http://www.toryburchs.us
    http://www.chromeheartsoutletonline.com
    http://www.jordan11retro.us.com
    http://www.filashoes.org
    http://www.adidasstansmith.uk
    http://www.offwhitexjordan1.com
    http://www.air-max.us.com
    http://www.yeezy-boost.us.com
    http://www.yesyeezy.shop......tml
    http://www.jimmychoo-shoes.us.com
    http://www.nikeairmax2019.us.com
    http://www.hermes-handbags.us.com
    http://www.nikepolo.us
    http://www.outletlacoste.us.com
    http://www.fila-shoes.us.com
    http://www.goldengoosesneakers.us
    http://www.jordan13.us.com
    http://www.nikereact.org
    http://www.bapehoodie.us
    http://www.ferragamobelt.us
    http://www.adidasnmduk.com
    http://www.monclerjackets.us
    http://www.kyrieirving-shoes.us.com
    http://www.lacostepolo.us.com
    http://www.yesyeezy.shop......tml
    http://www.yeezy-shoes.us.org
    http://www.adidasyeezy.co.uk
    http://www.coachoutletstorefactory.com
    http://www.jordan4.us.com
    http://www.yeezy-boost350.us.com
    http://www.goyard.us.com
    http://www.hogan-outlet.us.com
    http://www.jordansshoes.us.org
    http://www.yslhandbags.net
    http://www.fitflops-saleclearance.us.com
    http://www.katespadehandbags-outlet.us.com
    http://www.yeezyboost350v2shoes.us.com
    http://www.adidas-tubular.us.com
    http://www.asics-shoes.us.org
    http://www.hermesbelts.com
    http://www.yesyeezy.shop......tml
    http://www.yeezyshoesuk.com
    http://www.nike-roshe.us.com
    http://www.nikejordans.us.com
    http://www.outletmichael-kors.us.com
    http://www.supremeclothing.us
    http://www.goyardbags.us
    http://www.adidas-crazyexplosive.us.com
    http://www.michael-kors-handbags.com.co
    http://www.adidasiniki.us
    http://www.yeezysshoes.org
    http://www.guccibelt.us.com
    http://www.kd11.us.com
    http://www.yesyeezy.shop
    http://www.hermesonlineshop.com
    http://www.longchamphandbags.co.uk
    http://www.lebron16.us
    http://www.hermes-birkin.us.com
    http://www.goldengoose.us.com
    http://www.yesyeezy.shop/supreme-x-nike-air-more-uptempo-varsity-redwhite-902290600-p-592.html
    http://www.kobesneakers.com
    http://www.coachoutletssale.com
    http://www.kd11.us
    http://www.nikeair-max.us.com
    http://www.hermeshandbags.us.org
    http://www.caterpillarboots.us.com
    http://www.airmax90.us.org
    http://www.coachoutlets.name
    http://www.offwhite.us.com
    http://www.yeezyboost-350v2.us.com
    http://www.adidassuperstar.us.com
    http://www.coachsonline.us.com
    http://www.yesyeezy.shop/adidas-yeezy-boost-350-v2-cream-white-cp9366-p-423.html
    http://www.jordan12.us.com
    http://www.golden-goose.us.com
    http://www.calvinkleinoutlet.us.com
    http://www.lebron16.us.com
    http://www.converseoutlet.us.com
    http://www.yesyeezy.shop/adidas-yeezy-boost-350-v2-beluga-solar-red-bb1826-p-422.html
    http://www.hardenshoes.us.com
    http://www.kobebasketballshoes.net
    http://www.goyardhandbags.org
    http://www.yeezy-boosts.us.com
    http://www.lebronjames-shoes.us.com
    http://www.nikebasketballshoes.us.com
    http://www.nike-shox.us.com
    http://www.balenciagashoes.us.com
    http://www.lebron15.net
    http://www.louboutinshoes.uk
    http://www.jordanshoes.org.uk
    http://www.yesyeezy.shop/balenciaga-17fw-triple-s-trainer-black-red-mens-w05m23972-p-613.html
    http://www.jordanssneakers.us.com
    http://www.balenciaga.us.com
    http://www.nikesneakers.us.com
    http://www.adidas-pureboost.us.com
    http://www.nike-airmax2017.us.com
    http://www.fakerolex.us.com
    http://www.nikeflyknit.us.com
    http://www.outletonline-michaelkors.us.org
    http://www.paulgeorgeshoes.us.com
    http://www.ultraboost.us.com
    http://www.adidasstansmith.us.com
    http://www.jordan-retro.us.com
    http://www.shoesjordan.us.com
    http://www.reebokoutlet.us.org
    http://www.russellwestbrookshoes.us.com
    http://www.yeezyboost-350.uk
    http://www.pandorabracelet.in.net
    http://www.airjordanretro.uk
    http://www.adidasyeezys.us.com
    http://www.outlettimberland.us.org
    http://www.kyrie4.org
    http://www.yesyeezy.shop/offwhite-air-jordan-1-retro-chicago-the-ten-aa3834101-p-837.html
    http://www.yesyeezy.shop/air-jordan-1-og-game-royal-blue-mens-555088403-p-682.html
    http://www.goldengooseoutlet.us
    http://www.valentinosshoes.us
    http://www.kyrie3.us.com
    http://www.nhljerseysshop.us.com
    http://www.nfljerseys.us.org
    http://www.coachoutletsfactory.com
    http://www.long-champ.us.com
    http://www.supremehoodie.us.com
    http://www.michael-kors-handbags.org.uk
    http://www.hermes-belt.us.com
    http://www.yeezy700.us.com
    http://www.nikefoamposite.us.com
    http://www.lebron16.net
    http://www.yesyeezy.shop/offwhite-x-nike-air-presto-black-aa3830002-p-291.html
    http://www.lacostepolosshirts.com
    http://www.yesyeezy.shop/adidas-yeezy-desert-rat-500-blush-db2908-p-425.html
    http://www.yeezysuk.com
    http://www.mbtshoesonline.com
    http://www.handbagsmichaelkors.com
    http://www.goyardhandbags.us.com
    http://www.adidasoutletonline.com
    http://www.chromehearts.com.co
    http://www.fila.us.org
    http://www.kevindurant-shoes.us.com
    http://www.vapormaxshoes.us
    http://www.michael--korsoutlet.us.org
    http://www.michaelkors-outletfactory.us.org
    http://www.chromehearts.name
    http://www.yesyeezy.shop/balenciaga-17fw-triple-s-black-pink-women-sneaker-483523w06e38080-p-618.html
    http://www.yeezyboost.in.net
    http://www.offwhiteclothing.us.com
    http://www.birkinbag.us.com
    http://www.hermesbelts.co.uk
    http://www.balenciagashoes.us.org
    http://www.bape-hoodie.us.com
    http://www.mlbjerseys.in.net
    http://www.vans-outlet.us.com
    http://www.jordan6.us.com
    http://www.michaeljordanshoes.us.com
    http://www.curry5.us.com
    http://www.polosralphlaurenuk.com
    http://www.curry4shoes.us.com
    http://www.adidasgazelle.us.com
    http://www.lacosteonlineshop.us.com
    http://www.goyard-handbags.us.com
    http://www.retro-jordans.us.com
    http://www.michael-korsoutlets.us
    http://www.goldengoose-outlet.us.com
    http://www.offwhitehoodie.us.com
    http://www.goldengoose-sneakers.com
    http://www.off-whiteshoes.us.com
    http://www.adidasyeezys.us
    http://www.kobe-shoes.us.com
    http://www.monclersoutlet.us.com
    http://www.ferragamobelt.us.org
    http://www.michaelkors-outletonlines.us.com
    http://www.nikecortez.us.com
    http://www.yeezy500.us
    http://www.adidasultraboost.us.org
    http://www.jordansforcheap.us.com
    http://www.canada-goose.in.net
    http://www.nikeairmax2018.us.com
    http://www.goldengoose-sneakers.us
    http://www.nikereact.us.com
    http://www.adidasnmds.us.com
    http://www.nikehuaracheshoes.us.com
    http://www.airmax270.us.com
    http://www.cheapnbajerseyswholesales.us.com
    http://www.nike-huarache.com
    http://www.adidasnmds.com
    http://www.yeezyboost.com.co
    http://www.nikeairforce1.us.com
    http://www.adidaseqts.com
    http://www.yeezy-shoes.org.uk
    http://www.yesyeezy.shop/nike-air-max-197-sean-wotherspoon-aj4219400-p-66.html
    http://www.adidasshoesonline.com
    http://www.kd-10.us
    http://www.longchampshandbags.us
    http://www.adidaszxflux.com
    http://www.monclerjacket.net
    http://www.rolex-replica.us.com
    wwwe
  2. leesj020925@naver.com
    처음 수강중이라 어렵고 헷갈리기도 하지만 재밌기도 하네요
  3. 연수아빠
    수강 완료!!
버전 관리
egoing
현재 버전
선택 버전
graphittie 자세히 보기