Nodejs - db 연결해보기

정종찬·2022년 5월 8일
0
server.js

const express = require('express');
const app = express();
const nunjucks = require('nunjucks');
const router = require('./routes')


app.set('view engine', 'html')
nunjucks.configure('views', {
    express:app,
})

app.use(express.urlencoded({extended:true}))
app.use(router)

app.listen(3000, () => {
    console.log('서버 시작')
})
routes/index.js

const express = require('express')
const router = express.Router()
const boardRouter = require('./board')

router.get('/', (req, res) => {
    res.render('index')
})

router.use('/board', boardRouter)

module.exports = router
routes/board/index.js

const express = require('express')
const router = express.Router()

const boardController = require('./board.controller.js')

router.get('/list', boardController.list)
router.get('/view', boardController.view)

module.exports = router
routes/board/board.controller.js

const pool = require('../../db.js')

const list = async (req, res) => {
    try{
        const [result] = await pool.query(`SELECT * FROM board`)
        console.log(result)
        res.render('board/list', {
            items:result,
        })
    } catch (e) {
        console.log('에러 났지')
    } 
}

const view = (req, res) => {
    res.render('board/view', )
}

module.exports = {
    list,
    view
}
views/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    메인페이지
    <a href="/board/list">게시판가기</a> 
</body>
</html>
views/board/list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    list
    <table>
        <tr>
            <td>번호</td>            
            <td>제목</td>
            <td>내용</td>
            <td>글쓴이</td>
            <td>작성일</td>
            <td>좋아요</td>
            <td>조회수</td>
        </tr>
        {% for item in items %}
        <tr>
            <td><a href="/board/view?idx={{item.idx}}"></a>{{item.idx}}</td>            
            <td>{{item.subject}}</td>
            <td>{{item.content}}</td>
            <td>{{item.name}}</td>
            <td>{{item.date}}</td>
            <td>{{item.like}}</td>
            <td>{{item.hit}}</td>
        </tr>
        {% endfor %}
    </table>
    <a href="/board/list">게시판가기</a> 
</body>
</html>
views/board/view.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    view
    <a href="/board/list">글목록가기</a> 
</body>
</html>

profile
dalssenger

0개의 댓글