TODO 프로젝트 – 7. 목록 표시하기

MySql에 입력된 더미 데이터를 list 페이지에 노출시켜보겠습니다.
입력된 데이터는 타이틀과 내용으로 이루어져 있습니다.

1.프론트 처리 (frontend/src/components/page/list.vue)

template 영역

<template>
    <div class="list">
        <h2 class="comm__title">
            LIST
        </h2>
        <ul class="comm__list">
            <li v-for="(item,index) in todoItems" :key="index" :class="{ isEnd : item.todos_status == 1 }">
                <div class="comm__list-chk">
                    <input type="checkbox" class="chk" :checked="item.todos_status == 1" @change="todoCheck(item.todos_id,$event)">
                </div>
                <div class="comm__list-tit">{{item.todos_title}}</div>
                <div class="comm__list-con">
                    {{item.todos_desc}}
                </div>
            </li>
        </ul>
        <div class="comm__list-bottom">
            <a href="/add" class="btn btn--large btn--confirm">
                ADD
            </a>
        </div>
    </div>
</template>

구문별로 살펴보면 아래와 같습니다.

:class=”{ isEnd : item.todos_status == 1 } – 할일의 상태가 완료일때는 isEnd라는 클래스 추가
:checked=”item.todos_status == 1″ – 할일의 상태가 완료일때는 체크 처리
@change=”todoCheck(item.todos_id,$event)” – 체크상태가 변경되면 함수 실행처리

script 영역

<script>
export default  {
    data() {
        return {
            todoItems : [],
        }
    },
    methods : {
        todoCheck : function (id,event) {
            this.$http.post('/api/todo/check',{id : id, isChk : event.target.checked}).then((response) => {
                console.log(response.data);
                this.getListAll();
            });
        },
        getListAll : function () {
            this.$http.get('/api/todo').then((response) => {
                this.todoItems = response.data.map(function (data) {
                    return data;
                });
            });
        }
    },
    created () {
        this.getListAll();
    }
}
</script>
        getListAll : function () {
            this.$http.get('/api/todo').then((response) => {
                this.todoItems = response.data.map(function (data) {
                    return data;
                });
            });
        }

/api/todo의 주소로 API를 호출하여 todoItems 배열에 넣는처리를 합니다.

        todoCheck : function (id,event) {
            this.$http.post('/api/todo/check',{id : id, isChk : event.target.checked}).then((response) => {
                console.log(response.data);
                this.getListAll();
            });
        },

할일 체크시에 /api/todo/check를 호출하고 인자로 id값과 체크여부를 전달합니다.
DB적용 여부를 true,false로 콘솔에 노출하고, 리스트에 실시간 적용을 위해 리스트를 받아오는 함수를 다시 실행합니다.

2.API 처리 (backend/app.js)

app.get('/api/todo', function (req,res) {
    var userNo = req.session.userNo;
    if (!userNo) {
        res.json({
            success : false,
            message : '로그인 해주세요.'
        });
    } else {
        connection.query(
            "SELECT * from todos WHERE `todos_author` = " + userNo ,
            function (error, results, fields) {
                if (error) console.log(error);
                res.json({
                    success : true,
                    data : results
                })
            }
        );
    }
});

app.post('/api/todo/check',function (req,res,next) {
    var params = [req.body.isChk,req.body.id];
    connection.query(
        "UPDATE todos SET `todos_status` = ? WHERE `todos_id` = ?", params,
        function (error, results, fields) {
            if (error) console.log(error);
           res.send(true);
        }
    );
});

API 파일에서 리스트를 가져오는 API 소스를 수정합니다.
세션값 여부를 체크하여 그에 따른 결과를 리턴해 줍니다.
할일체크 API에서는 받은 매개변수로 쿼리를 돌려서 할일 완료 여부를 변경해줍니다.

body parser 사용

전달된 파라미터를 req.body.파라미터명 형태로 사용하기 위해서는 body-parser의 설치가 필요합니다.
https://www.npmjs.com/package/body-parser

npm install body-parser
Express/Connect top-level generic 예제
var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

app.use(function (req, res) {
  res.setHeader('Content-Type', 'text/plain')
  res.write('you posted:\n')
  res.end(JSON.stringify(req.body, null, 2))
})
Express route-specific 예제
var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  res.send('welcome, ' + req.body.username)
})

// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
  // create user in req.body
})
hange accepted type for parsers 예제
var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))

// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))

// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))