Controller / Router

index.js (router class)

const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');

const controller = require('./controller');

router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));

router.get('/posts', controller.select);
router.post('/posts', controller.insert);
router.delete('/posts/:id', controller.remove);
router.put('/posts/:id', controller.update);

module.exports = router;

controller.js (controller class)

const mysql = require('mysql2');
const { createCipher } = require('crypto');

// 데이터베이스 연결
const con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '1',
    database: 'express_db'
});

const select = ('/posts', async (req, res) => {
    try {
        const sql = 'select * from products'
        const [row, fields] = await con.promise().query(sql);
        console.log(row);
        res.send(row);
    } catch(err) {
        res.send('Error!');
    }
});

const insert = ('/posts', (req, res) => {
    const sql = 'insert into products set ?'
    console.log(req.body);
    // console.log(req.)
    con.query(sql, req.body, function(err, result, fields) {
        if(err) throw err;
        console.log(result);
        res.send('등록이 완료되었습니다.');
    });
});

const remove = ('/posts/:id', (req, res) => {
    const sql = 'delete from products where id=?';
    con.query(sql, [req.params.id], function(err, result, fields) {
        if(err) throw err;
        console.log(result);
        res.redirect('/');
    })
});

const update = ('/posts/:id', (req, res) => {
    const sql = 'update products set ? where id=' + req.params.id;
    con.query(sql, req.body, function(err, result, fields) {
        if(err) throw err;
        console.log(result);
        res.redirect('/');
    })
})


module.exports = {
    select: select,
    insert: insert,
    remove: remove,
    update: update
}

app.js

const path = require('path');
const mysql = require('mysql2');
const express = require('express')
const bodyParser = require('body-parser');
const { createCipher } = require('crypto');
const app = express()
const port = 3000

// 데이터베이스 연결
const con = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '1',
    database: 'express_db'
});

// 브라우저에서 입력한 값들은 POST 요청 결과로 전송 -> 처리하려면 bodyParser 필요
app.use(bodyParser.urlencoded({ extended: true }));

// router class
const posts = require('./index.js');

app.use('/', posts);
// 루트 경로에 위의 posts 객체(index.js) 등록

module.exports = app;
app.listen(port, () => console.log(`Example app listening on port ${port}`));

참고 출처 : https://jinbroing.tistory.com/160

좋은 웹페이지 즐겨찾기