nodeJS+express+mysql模块封装之服务器渲染小demo
- 创建一个小项目
npm init
- 下载相关中间件(根据package.js来下载)
- package.js
- 目录结构
- index.js代码
const express = require('express'); const path = require('path'); const template = require('art-template'); const bodyParser = require('body-parser'); const router = require('./router.js') const app = new express(); // 启动静态 app.use('/static', express.static(path.join(__dirname, 'public'))) // 设置模板引擎 // 设置模板 引擎的路径 app.set('views',path.join(__dirname,'views')); // 设置模板引擎 app.set('view engine','art'); // 使express 兼容 art-template 模引擎 app.engine('art',require('express-art-template')); app.use(bodyParser.urlencoded({ extended: false})); app.use(bodyParser.json()); // 配置路由 app.use(router); // 监听端口 const server = app.listen(8081, ()=> { const host = server.address().address const port = server.address().port console.log("应用实例,访问地址为 http://%s:%s", host, port) })
- 利用回调函数的性质完成db.js:
const mysql = require('mysql'); exports.base = (sql,data,callback) => { const connection = mysql.createConnection({ host:'主机地址', user:'root', password:'你的mysql密码', database:'book' }); connection.connect(); connection.query(sql,data,function(error,results,fields){ if(error) throw error; callback(results); }) connection.end(); }
- 建立router.js路由模块(这里以图书管理为例):
/** * 路由模块 */ const express = require('express'); const router = express.Router(); const service = require('./serveice.js') // 路由处理 router.get('/',service.showIndex); router.get('/toBook',service.toAddBook); router.post('/addBook',service.addBook); router.get('/toEditBook',service.toEditBook); router.post('/editBook',service.editBook); router.get('/deleteBook',service.deleteBook) // router.get('/dBook',service.deleteBook) module.exports = router;
- 业务层抽离,专心业务的书写,建立serveice.js业务模块
/** * 业务模块(处理具体的业务) */ const data = require('./data.json'); const path = require('path'); const db = require('./db.js') const fs = require('fs'); // 自动生成图书编号 let maxBookCode = ()=>{ let arr= []; data.forEach((item) => { arr.push(item.id); }); return Math.max.apply(null,arr); } // 渲染主页面 exports.showIndex = (req,res) => { let sql = 'select * from book'; db.base(sql,null,(result) => { res.render('index',{list:result}) }); } exports.toAddBook = (req,res)=>{ res.render('addbook',{}) } exports.addBook = (req,res)=>{ // 获取表单数据 let info = req.body; console.log(info) let book = {}; for(let key in info){ book[key] = info[key]; } let sql = 'insert into book set ?'; db.base(sql,book,(result) => { // console.log(result); if(result.affectedRows >= 1){ res.redirect('/'); } }) } exports.toEditBook= (req,res)=>{ let id = req.query.id; let sql = "select * from book where id = ?"; let data = [id]; db.base(sql,data,(result) => { res.render('editBook',result[0]); }) } exports.editBook= (req,res) => { let info = req.body; console.log(info.description); let sql = "update book set name=?,author=?,category=?,description=? where id=?"; let data = [info.name,info.author,info.category,info.description,info.id]; db.base(sql,data,(result) => { if(result.affectedRows >= 1){ res.redirect('/'); } }); } exports.deleteBook = (req,res) => { let id = req.query.id; let sql = ` delete from book where id = ?; `; let data = [id]; db.base(sql,data,(result)=>{ if(result.affectedRows >= 1){ res.redirect('/'); } }) } // exports.dBook = (req,res) => { // let id = req.query.id; // let sql = "ALTER TABLE book ADD id INT NOT NULL PRIMARY KEY AUTO_INCREMENT FIRST;" // }
- 数据交互采用的art-template
- 目录结构
-
- 主页面,index.art:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>图书馆里系统</title> <link rel="stylesheet" type="text/css" href="/static/css/style.css"> </head> <body> <div class="title">图书馆里系统 <a href="/toBook">添加图书</a></div> <div class="content"> <table cellpadding = "0" cellsapcing = "0"> <thead> <tr> <th>编号</th> <th>名称</th> <th>作者</th> <th>类别</th> <th>描述</th> <th>操作</th> </tr> </thead> <tbody> {{ each list}} <tr> <td>{{ $value.id }}</td> <td>{{ $value.name }}</td> <td>{{ $value.author }}</td> <td>{{ $value.category }}</td> <td>{{ $value.description }}</td> <td><a href="/toEditBook?id={{$value.id}}">修改</a>|<a class='del' href="/deleteBook?id={{$value.id}}">删除</a></td> </tr> {{ /each}} </tbody> </table> </div> </body> </html>
- 添加图书个管理图书界面(addBook.art,editBook.art):
// addBook 添加图书 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>添加图书</title> </head> <body> <div>添加图书</div> <form action="/addBook" method="post"> 编号: <input type="text" name="id" id=""><br> 名称: <input type="text" name="name" id=""><br> 作者: <input type="text" name="author" id=""><br> 类别: <input type="text" name="category" id=""><br> 描述: <input type="text" name="description" id=""><br> <input type="submit" value="提交"> </form> </body> </html>
// editBook编辑图书 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>编辑图书</title> </head> <body> <div>编辑图书</div> <form action="/editBook" method="post"> 编号: <input type="text" name="id" value = "{{id}}"><br> 名称: <input type="text" name="name" value = "{{ name }}"><br> 作者: <input type="text" name="author" value = "{{ author }}"><br> 类别: <input type="text" name="category" value = "{{ category }}"><br> 描述: <input type="text" name="description" value = "{{ description }}"><br> <input type="submit" value="提交"> </form> </body> </html>
- 输入命令
nodemon index.js
来跑自己的程序吧!体验喜悦的时刻到了!