Node.js 를 MySQL과 연동하여 아래와 같은 글목록을 만들어본다.


글 목록 만들기 

 

 

app_mysql.js를 작성하고, DB연결을 한다.

// MySQL로 글목록 만들기.

var express = require('express');
var app = express();
var bodyParser = require('body-parser')
var fs = require('fs')

// POST 방식 처리할 때, body 속성을 가공해준다 
app.use(bodyParser.urlencoded({extended: false}))

// DB 연결 
var mysql      = require('mysql');
var conn = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '111111',
  database : 'o2'
});

conn.connect();

 

템플릿 엔진과 템플릿  파일 디렉토리를 명시해준다.

//템플릿 엔진 (views 들을 위치할 디렉토리 적어준다)
app.set('views', './views_mysql');
//템플릿 엔진 종류 명시 
app.set('view engine', 'jade');

app.locals.pretty = true;

 

라우팅 처리 

 

topic 이나 topic/id 를 통해 접근하면 글 목록이 보인다. 

 

app.get() 함수의 URL 부분을 배열로 만든다. 

그리고 id, title을 가지고 글목록을 만든다. 

app.get(['/topic', '/topic/:id'], function(req,res){

    var sql = 'SELECT id, title FROM topic';
    conn.query(sql, function(err, topics, fields){
      
    })
})

 

상세보기 내용을 가지고 와서 view 파일에 띄워준다.

res.render() 함수를 사용하여 view 라는 이름의 템플릿을 이용한다. 

app.get(['/topic', '/topic/:id'], function(req,res){

    var sql = 'SELECT id, title FROM topic';
    conn.query(sql, function(err, topics, fields){
        // 사용자가 id를 URL에 물고들어왔는지. 
        var id = req.params.id;

        if(id){ // 상세 보기 한다 
            var sql = 'SELECT * FROM topic WHERE id=?';
            conn.query(sql, id, function(err, rows, fields){
                if(err){
                    console.log(err);
                    res.status(500).send('Internal Server Error')
                }else{
                    res.render('view', {topics:topics, topic:rows[0]})
                }
            });
        }else{
            res.render('view', {topics:topics});
        }
    })
})

 

view.jade 템플릿 파일 

 

article태그 쪽을 보자. 

topic 이라는 값이 파라미터로 넘어 온다면, topic.title, topic.description, topic.author를 이용하여 상세보기 화면을 보여준다.

그렇지 않고 제목을 클릭 안했다면, Welcome만 띄워준다.     

doctype html
html
    head
        meta(charset='utf-8')
    body
        h1
            a(href='/topic') Server Side JavaScript
        ul  
            each topic in topics
                li
                    a(href='/topic/'+topic.id)=topic.title
        article
            if topic
                h2=topic.title
                =topic.description
                div='by '+topic.author
            else
                h2 Welcome!
                | This is server side javascript tutorial.

        a(href='/topic/add') add

 

 


글 작성 

 

맨 밑에 add 버튼을 누르면 입력폼이 나타나고, 내용이 DB 에 INSERT 되게 하자.

app.get('/topic/add', function(req, res))

새 글을 쓰는 입력 폼과 포스트 처리를 하는 함수가 필요하다. 

 

app.post('/topic/add',function(req, res))

POST 처리는 query() 함수로 DB에 INSERT 해주고, 작성이 완료된 페이지로 리다이렉션을 포함한다.

conn.query() 함수와 res.redirect() 함수.

// 새 글 쓰기 
app.get('/topic/add', function(req, res){
    var sql = 'SELECT id, title FROM topic';
    conn.query(sql, function(err, topics, fields){
        if(err){
            console.log(err);
            res.status(500).send('Internal Server Error')
        }
        res.render('add', {topics:topics})
    })  

})

// POST 처리
app.post('/topic/add',function(req, res){
    var title = req.body.title
    var description = req.body.description
    var author = req.body.author

    var sql = 'INSERT INTO topic (title, description, author) VALUES(?, ?, ?)'

    conn.query(sql, [title, description, author], function(err, result, fields){
        if(err){
            console.log(err);
            res.status(500).send('Internal Server Error')
        }else{
        // 작성 완료된 페이지로 리다이렉션 
        res.redirect('/topic/'+result.insertId)
        }
    })
 
})

app.get(['/topic', '/topic/:id'], function(req,res){

    var sql = 'SELECT id, title FROM topic';
    conn.query(sql, function(err, topics, fields){
        // 사용자가 id를 URL에 물고들어왔는지. 
        var id = req.params.id;

        if(id){ // 상세 보기 한다 
            var sql = 'SELECT * FROM topic WHERE id=?';
            conn.query(sql, id, function(err, rows, fields){
                if(err){
                    console.log(err);
                    res.status(500).send('Internal Server Error')
                }else{
                    res.render('view', {topics:topics, topic:rows[0]})
                }
            });
        }else{
            res.render('view', {topics:topics});
        }
    })
})

 

입력 폼 템플릿 add.jade 

doctype html
html
    head
        meta(charset='utf-8')
    body
        h1
            a(href='/topic') Server Side JavaScript
        ul  
            each topic in topics
                li
                    a(href='/topic/'+topic.id)=topic.title

        article
            form(action='/topic/add', method='post')
                p
                    input(type='text' name='title' placeholder='title')
                p
                    textarea(name='description' placeholder='description')
                p
                    input(type='text' name='author' placeholder='author')
                p
                    input(type='submit')

                


 

글 편집 

 

글 제목을 클릭하면 상세 화면이 나온다. 

이 때, edit 버튼을 클릭하면 글을 편집할 수 있게 코드를 추가해보자. 

글을 읽어와서 입력 폼에 뿌려놔줘야 편집이 가능하다. 

그래서 글 작성과 글 읽기 기능을 이해하고 있어야 편집 기능 만들기가 가능하다.

 

 

view.jade 템플릿 

 

view.jade를 열어서 edit 버튼을 추가한다. 

맨 아래쪽에, topic 값이 있으면, edit 버튼이 보이도록 한다. 

왜냐하면 글 제목을 클릭 했을 때만 edit 버튼이 보이도록 하고 싶기 때문이다.

(예를 들어, /topic 에서는 안보이고, /topic/5 에서는 보인다.)

doctype html
html
    head
        meta(charset='utf-8')
    body
        h1
            a(href='/topic') Server Side JavaScript
        ul  
            each topic in topics
                li
                    a(href='/topic/'+topic.id)=topic.title
        article
            if topic
                h2=topic.title
                =topic.description
                div='by '+topic.author
            else
                h2 Welcome!
                | This is server side javascript tutorial.

        ul
            li
                a(href='/topic/add') add
            if topic
                li
                    a(href='/topic/'+topic.id+'/edit') edit

 

 

edit.jade 템플릿 

 

편집을 위한 입력폼을 보여주는 템플릿이다. 

view.jade 에서 article 부분 내부를 지우고, 그 안에 add.jade 템플릿에서 썼던 form을 가져와 붙여넣는다. 

 

글 목록 화면에서 edit 버튼을 누르면 편집 폼으로 이동한다
편집 폼에는 내용이 이미 쓰여 있고, edit 버튼은 없앤다.

 

기존의 컨텐츠를 입력폼에 넣어서 보여줘야 하기 때문에, input 태그 내부에 value 속성을 넣어준다.

textarea는 형식이 조금다르다. 괄호 안에 속성 써주는게 아니라, 괄호 옆에 이퀄 (=)을 써준다.  

form 의 action 태그는 topic.id 를 넣는다. 

폼의 내용들을 DB에 저장하기 위해 /edit URL을 명시해준다. 

doctype html
html
    head
        meta(charset='utf-8')
    body
        h1
            a(href='/topic') Server Side JavaScript
        ul  
            each topic in topics
                li
                    a(href='/topic/'+topic.id)=topic.title
        article
            form(action='/topic/'+topic.id+'/edit', method='post')
                p
                    input(type='text' name='title' placeholder='title'
                    value=topic.title)
                p
                    textarea(name='description' placeholder='description')
                        =topic.description
                p
                    input(type='text' name='author' placeholder='author'
                    value=topic.author)
                p
                    input(type='submit')
        ul
            li
                a(href='/topic/add') add

 

POST 처리는 id 에 따라 DB에 update 할 함수를 만들고 라우팅을 해준다. 

 

// 편집 내용 POST를 query() 함수로 DB UPDATE. 그리고 리다이렉션 

app.post(['/topic/:id/edit'], function(req,res){
    var title = req.body.title;
    var description = req.body.description;
    var author = req.body.author;
    var id = req.params.id;
    var sql = 'UPDATE topic SET title=?, description=?, author=? WHERE id=?';

    conn.query(sql, [title, description, author, id], function(err, result, fields){
        if(err){
            console.log(err);
            res.status(500).send('Internal Server Error')
        }else{
            // 에러 없으면 리다이렉션 
            res.redirect('/topic/'+id);
        }
    })
})

 


글 삭제

 

글을 클릭했을 때 편집 기능이 보이는 것 처럼, 글 삭제도 글을 클릭했을 때만  보이도록 한다. 

veiw.jade 템플릿 맨 아래에 버튼하나 추가한다. 

 

view.jade 템플릿

doctype html
html
    head
        meta(charset='utf-8')
    body
        h1
            a(href='/topic') Server Side JavaScript
        ul  
            each topic in topics
                li
                    a(href='/topic/'+topic.id)=topic.title
        article
            if topic
                h2=topic.title
                =topic.description
                div='by '+topic.author
            else
                h2 Welcome!
                | This is server side javascript tutorial.

        ul
            li
                a(href='/topic/add') add
            if topic
                li
                    a(href='/topic/'+topic.id+'/edit') edit
                li
                    a(href='/topic/'+topic.id+'/delete') delete

 

app_mysql.js에 /delete 를 처리할 라우팅 함수를 하나 만든다. 

 

 

728x90

'프로그래밍 > Node.js' 카테고리의 다른 글

Node.js npm pm2  (0) 2020.04.05
MySQL 명명 규칙  (0) 2020.03.23
MySQL select insert delete update  (0) 2020.03.21
MySQL 사용  (0) 2020.03.18
MySQL 설치  (0) 2020.03.16

Node.js 서버를 만드는 코드를 해석해본다. 

 

https://nodejs.org/en/about/

 

About | Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

노드제이에스가 뭔가요?

 

홈페이지에 가보면, 이벤트 기반 비동기식 자바스크립트 런타임 환경이라는 설명이 있다. 

 

 

아래의 샘플코드를 해석해보자. 

 

 

일단 http 모듈 객체로 서버를 만든다. 

hostname, post 라는 변수를 만들어서 주소와 포트를 저장한다. 

 

아래의 코드는 createServer를 쉽게 풀어 쓴 것이다. 위의 샘플 코드와 똑같이 동작한다.

 

함수의 파라미터로 콜백함수가 들어가 있다.

콜백함수는 이름이 없는 익명함수로 들어가 있다. function() 

 

http 모듈의 createServer() 함수로 server 객체를 만든다. 

콜백함수의 파라미터에는 요청을 뜻하는 request, 응답을 뜻하는 response가 있다. 

 

클라이언트의 요청이 오면, 어떤 동작을  할 지 CreateServer() 내부에 써주는 것이다. 

클라이언트에게 해줄 작업은 전부 res 객체가 제공하는 함수를 사용한다.  

 

server 객체의 listien() 함수는 다양한 이유로 오래걸릴 수 있는 작업이다. 

그래서 listion() 수립이 완료되면, 콜백 으로 console.log() 를 출력하게 해놨다. 

 

 

728x90

'프로그래밍 > Node.js' 카테고리의 다른 글

Express app.use()  (0) 2020.03.14
Express  (0) 2020.03.13
동기 vs 비동기  (0) 2020.03.13
npm 모듈을 이용해보자  (0) 2020.03.13
Node.js 설치 , NPM 모듈 설치  (0) 2020.03.13

+ Recent posts