Node.js & MySQL 02

m1njae·2022년 1월 26일
1

22 Basic Challenge

목록 보기
24/25
post-thumbnail

홈페이지 구현

데이터를 파일로 저장했던 웹 사이트를 이제는 데이터를 데이터베이스에 저장하는 웹 사이트로 변경해보는 과정이다.
mysql.js 파일에 작성해놓았던 타인이 만들어놓은 모듈 코드를 웹 사이트 실행을 위해 main.js 파일에 작성해준다.

var mysql = require('mysql');
var db = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '비밀번호',
  database : 'opentutorials'
});
db.connect();

그리고 데이터베이스를 정상적으로 로드되는지 코드를 통해서 확인해준다.


// 수정 전 파일을 로드하는 코드
fs.readdir('./data', function(error, filelist){
          var title = 'Welcome';
          var description = 'Hello, Node.js';
          var list = template.list(filelist);
          var html = template.HTML(title, list,
            `<h2>${title}</h2>${description}`,
            `<a href="/create">create</a>`
          );
          response.writeHead(200);
          response.end(html);
        });
///////////////////////////////////////////////

// 데이터베이스를 로드하는 코드
db.query(`SELECT * FROM topic`, function(error,topics){
          console.log(topics);
          response.writeHead(200);
          response.end('Success');
        });


웹 사이트에는 정상적으로 'Success'라는 문구가 출력되고, 터미널에 내용이 출력되는 것을 확인 할 수 있다. 그래서 곧장 내가 만든 간단한 웹 사이트에 적용해보기로 하였다.

--topic table 생성
CREATE TABLE topic(
     id VARCHAR(100) NOT NULL,
    description TEXT NOT NULL,
     PRIMARY KEY(id));

-- id = major
INSERT INTO topic(id,description) VALUES('major','본문내용');

-- id = goal
INSERT INTO topic(id,description) VALUES('goal','본문내용');

-- id = BasicChallenge
INSERT INTO topic(id,description) VALUES('BasicChallenge','본문내용');


id값과 본문내용이 들어가있는 테이블을 생성해주었다. 기존에 텍스트 파일에 저장되어있던 데이터를 데이터베이스로 만들어준 것이다. 이후 데이터베이스를 연동시킬 수 있도록 코드를 수정해줬다.

// 수정 전 파일을 로드하는 코드
fs.readdir('./data', function(err, filelist){
           fs.readFile(`data/${queryData.id}.txt`,'utf8', function(err, description){
            var title = `${querytotitle(queryData.id)}`;
            var template = templateHTML(title, description,
            `<br><a href='/update?id=${queryData.id}'>🙇‍♂️내용 수정하기🙇‍♂️</a> <a href = '/'>&nbsp홈으로🏠</a><br>Life is always finding its own way`)
            response.writeHead(200);  
            response.end(template);
         });
       });

// 수정 후 데이터베이스를 로드하는 코드
db.query(`SELECT * FROM topic`, function(error,topic){
         if(error){
           throw error;
         }
         db.query(`SELECT * FROM topic WHERE id=?`,[queryData.id],function(error2,topic){
           if(error2){
             throw error2;
           }
           var title = `${querytotitle(queryData.id)}`;
           var template = templateHTML(title, topic[0].description,
           `<br><a href='/update?id=${queryData.id}'>🙇‍♂️내용 수정하기🙇‍♂️</a> <a href = '/'>&nbsp홈으로🏠</a><br>Life is always finding its own way`)
           response.writeHead(200);  
           response.end(template);
         })
       })

topic의 정보를 불러오지 못하거나, 특정 id의 정보를 가져오지 못했을 경우를 고려하여 throw error;를 작성해주었다. 그리고 topic 데이터는 배열에 담겨서 들어오기 때문에 topic을 배열로서 취급하여 topic[0].description으로 작성해주었다.

id값도 기존 쿼리스트링과 동일하게 잘 나타나고, 데이터베이스에 있는 내용들을 잘 출력하는 것을 확인할 수 있었다. 에러없이 바로 되니까 뭔가 신기하고 어색하고 그래.. 내일은 글 수정하는 부분을 구현해보도록 해야겠다.

참고

생활코딩 Node.js & MySQL

profile
할 수 있는 것부터 차근차근, 항해자의 공부 기록공간

0개의 댓글