1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| const express = require('express'); const mysql = require('mysql2');
const app = express(); const PORT = process.env.PORT || 3000; app.set('views', `${__dirname}/views`); app.set('view engine', 'ejs');
const connection = mysql.createConnection({ host: 'localhost', user: 'root', database: 'paging_test', });
app.get('/', (req, res) => { const pageNum = Number(req.query.pageNum) || 1; const contentSize = 10; const pnSize = 10; const skipSize = (pageNum - 1) * contentSize;
connection.query('SELECT count(*) as `count` FROM `articles`', (countQueryErr, countQueryResult) => { if (countQueryErr) throw countQueryErr; const totalCount = Number(countQueryResult[0].count); const pnTotal = Math.ceil(totalCount / contentSize); const pnStart = ((Math.ceil(pageNum / pnSize) - 1) * pnSize) + 1; let pnEnd = (pnStart + pnSize) - 1; connection.query('SELECT * FROM `articles` ORDER BY id DESC LIMIT ?, ?', [skipSize, contentSize], (contentQueryErr, contentQueryResult) => { if (contentQueryErr) throw contentQueryErr; if (pnEnd > pnTotal) pnEnd = pnTotal; const result = { pageNum, pnStart, pnEnd, pnTotal, contents: contentQueryResult, }; res.render('index', { articles: result, }); }); }); });
app.get('/view/:id', (req, res) => { const { id } = req.params; connection.query('SELECT * FROM `articles` WHERE id = ?', [id], (err, results) => { if (err) throw err; res.render('view', { article: results[0], }); }); });
app.listen(PORT, () => { console.log(`express is running on port ${PORT}`); });
|