본문 바로가기
WEB/Nodejs-mysql

[Nodejs-mysql] 데이터 가져와서 출력하기

by Ellen571 2020. 8. 5.

[생활코딩] MySQL로 홈페이지 구현

[생활코딩] MySQL로 상세보기 구현

 

 

데이터베이스 접속하기

 

var mysql = require('mysql');

var db = mysql.createConnection({
  host : 'localhost',
  user : 'root',
  password : 'abc123',
  database : 'opentutorials'
});

db.connect();

 

topic데이터 가져오기

 

main.js

if(pathname === '/'){

      if(queryData.id === undefined){ // 홈페이지
      
        db.query(`SELECT*FROM topic`, function(error, topics){
        // 쿼리문을 실행하고 그 결과 값을 topics로 가져옴
        
          var title = 'Welcome';
          var description = 'Hello, Node.js';
          var list = template.list(topics); // 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){
        // topic 데이터 가져오고 topics에 담음
        
          if(error){ throw error;}
          // 데이터를 가져오지 못하면 error를 던져서 애플리케이션을 중지 시킴
          
          db.query(`SELECT*FROM topic WHERE id=${queryData.id}`,function(error2, topic){
          // topic id중 queryData.id값과 일치하는 데이터를 가져와 topic에 담음
            
            if(error2){throw error2;}
            
            var title = topic[0].title; // topic은 배열로 값이 전달됨
            var description = topic[0].description;
            var list = template.list(topics);
            var html = template.HTML(title, list,            
                  `<h2>${title}</h2>${description}`,
                  ` <a href="/create">create</a>
                    <a href="/update?id=${sanitizedTitle}">update</a>
                    <form action="delete_process" method="post">
                      <input type="hidden" name="id" value="${sanitizedTitle}">
                      <input type="submit" value="delete">
                    </form>`
            );
            
            response.writeHead(200);
            response.end(html);
          });
        });
        
      }
      
}

 

사용자가 입력한 정보는 오염될 수 있기에 ${queryData.id}를 간접적 전달 필요

 

db.query(`SELECT*FROM topic WHERE id=?`,[queryData.id],function(error2, topic){
// ?의 값을 두번째 인자인 배열에 담아서 전달
// 공격에 의도가 있는 코드가 있는 것들이 세탁처리됨
            
  if(error2){throw error2;}

  var title = topic[0].title; // topic은 배열로 값이 전달됨
  var description = topic[0].description;
  var list = template.list(topics);
  var html = template.HTML(title, list,            
    `<h2>${title}</h2>${description}`,
    ` <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>`
  ); // queryData.id값으로 업데이트, 삭제
  
  response.writeHead(200);
  response.end(html);
});

 

 

 

tamplate.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){
  // 인자 topics에 main.js template.list(topics)의 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>`;
          // topics 각 id와 title 값이 링크 주소와 이름이 됨
          i = i + 1;
        }
        list = list+'</ul>';
   	return list;
  }
}