# express crud demo ### 備註:數據的存儲存在文件中 1.安裝express
npm install -S expressjavascript
2.寫入helloWord
const express=require('express')
const app=express();
app.get('/',function(req,res){html
res.send('hello word')
})
app.listen(3000,function(){java
console.log('server is running list:http://localhost:3000');
})git
3. 在項目的根目錄下建立views目錄,並引入art-template模板 [art-template模板官網](**http://aui.github.io/art-template/express/**) * 在app.js中加入模板配置,而後使用art-template模板
app.engine('html', require('express-art-template')); ```
從文件中讀取數據(獲取列表R)github
關鍵代碼以下express
//app.js app.get('/',function(req,res){ fs.readFile('./db.json',(err,data)=>{ if(err){ return res.status(500).send('server error') } res.render('index.html',{ students:JSON.parse(data.toString()).students }) }) })
//index.html <ul> {{each students}} <li> <div>{{$value.id}}</div> <div>{{$value.name}}</div> <div>{{$value.age}}</div> <div>{{$value.gender}}</div> <div>{{$value.hobbies}}</div> </li> {{/each}} </ul>
//db.josn { "students":[ { "id":1, "name":"張三", "age":"12", "hobbies":"吃飯睡覺打豆豆", "gender":0 },{ "id":2, "name":"張三", "age":"12", "hobbies":"吃飯睡覺打豆豆", "gender":0 },{ "id":3, "name":"張三", "age":"12", "hobbies":"吃飯睡覺打豆豆", "gender":0 },{ "id":4, "name":"張三", "age":"12", "hobbies":"吃飯睡覺打豆豆", "gender":0 },{ "id":5, "name":"張三", "age":"12", "hobbies":"吃飯睡覺打豆豆", "gender":0 },{ "id":6, "name":"張三", "age":"12", "hobbies":"吃飯睡覺打豆豆", "gender":0 },{ "id":1, "name":"張三", "age":"12", "hobbies":"吃飯睡覺打豆豆", "gender":0 } ] }
index.js文件內容以下npm
const express=require('express') const router=express.Router(); router.get('/',funciton(req,res,next){ })
app.js關鍵代碼以下json
const router=require('./routes/index'); app.use(router)
app.use(funciont(req,res,next){ console.log(0) next()//這裏的next方法必需要執行,不然程序會掛起 })
6.新增數據(A)api
<form action="/addmsg" method="POST"> <div> 姓名:<input type="text" name="name"> </div> <div> 年齡:<input type="text" name="age"> </div> <div> 愛好:<input type="text" name="hobbies"> </div> <div> 性別:<input type="radio" name="gender" value="0"> <input type="radio" name="gender" value="1"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form>
// 渲染add頁面 router.get('/addnews',function(req,res){ res.render('add.html') }) // post添加數據 router.post('/addmsg',function(req,res){ fs.readFile(path.resolve(__dirname,'../db.json'),function(err,data){ if(err){ console.log(err); return res.status(500).send('讀取數據失敗') } let resdata=JSON.parse(data.toString()) req.body.id=new Date().getTime(); resdata.students.unshift(req.body) fs.writeFile(path.resolve(__dirname,'../db.json'),JSON.stringify(resdata),(err)=>{ if(err){ res.status(500).send('寫入文件失敗') } res.redirect('/') }) }) })
students.js文件關鍵代碼以下app
const fs = require('fs') const path = require('path') const readUrl = path.resolve(__dirname, '../db.json') function find(callback) { if (!callback || typeof callback !== 'function') { throw new Error('need callback function') } fs.readFile(readUrl, function (err, data) { if (err) { return callback(err) } const str = data.toString() callback(null, JSON.parse(str).students) }) } /* 查詢全部數據 */ exports.find = find /*刪除數據 */ exports.delete = function (id, callback) { find(function (err, students) { if (err) { return callback && callback(err) } for (let key in students) { const item = students[key] if (item.id == id) { delete students[key] break; } } fs.writeFile(readUrl, function (error, data) { if (error) { return callback && callback(error) || '刪除失敗' } callback && callback('刪除成功') }) }) } /* 更新數據 */ exports.update = function (updateData, callback) { find((err, students) => { for (let key in students) { const item = students[key] if (updateData.id == item.id) { students[key] = { ...students[key], ...updateData } } } fs.writeFile(readUrl, JSON.stringify({ students: students }), function (err) { if (err) { return callback && callback(err) || '更新失敗' } callback && callback(err) || '更新成功' }) }) } // 新增 exports.add = function (addData, callback) { find((err, students) => { students.unshift(addData) fs.writeFile(readUrl, JSON.stringify({ students: students }), function (err) { if (err) { return callback && callback(err) || '新增失敗' } callback && callback(err) || '新增成功' }) }) } // 根據id獲取具體的某一條數據 exports.getDataByid = function (id, callback) { find(function (err, students) { let curData = null; for (let key in students) { if (students[key].id == id) { curData = students[key] break; } } callback(curData) }) } // 刪除 exports.delete=function(id,callback){ find(function(err,students){ for (let key in students) { if (students[key].id == id) { students.splice(key,1) break; } } console.log(students); fs.writeFile(readUrl,JSON.stringify({students:students}),function(err){ if(err){ return callback(err) } callback('刪除成功') }) }) }
8.優化路由文件,核心代碼以下
const studentsUtil=require('../utils/students') // 渲染列表 router.get('/', function (req, res, next) { studentsUtil.find(function(err,students){ res.render('index.html', { students: students }) }) }) // 渲染add頁面 router.get('/addnews', function (req, res) { res.render('add.html') }) // post添加數據 router.post('/addmsg', function (req, res) { const data=req.body; data.id=new Date().getTime() studentsUtil.add(data) res.redirect('/') })
9.編輯數據(U)
<form action="/editMsg" method="POST"> <input type="hidden" name="id" value="{{id}}"> <div> 姓名:<input type="text" name="name" value="{{name}}"> </div> <div> 年齡:<input type="text" name="age" value="{{age}}"> </div> <div> 愛好:<input type="text" name="hobbies" value="{{hobbies}}"> </div> <div> 性別:<input type="radio" name="gender" value="0" > <input type="radio" name="gender" value="1"> </div> <button type="submit" class="btn btn-primary">Submit</button> </form>
在路由文件中新增以下代碼(routes/index.js)
// 渲染編輯頁面 router.get('/editPage',function(req,res){ studentsUtil.getDataByid(req.query.id,function(students){ // console.log(students); res.render('edit.html',{ ...students }) }) }) // 提交編輯頁面 router.post('/editMsg',function(req,res){ const data=req.body; studentsUtil.update(data,function(){ res.redirect('/') }) })
10.刪除數據(D)
在views/index.html中新增刪除按鈕
<ul> {{each students}} <li> <div>{{$value.id}}</div> <div>{{$value.name}}</div> <div>{{$value.age}}</div> <div>{{$value.gender}}</div> <div>{{$value.hobbies}}</div> <a href="/editPage?id={{$value.id}}">編輯</a> <a href="/deletedata?id={{$value.id}}">刪除</a> </li> {{/each}} </ul>
routes/index.js核心代碼以下
// 刪除數據 router.get('/deletedata',function(req,res){ studentsUtil.delete(req.query.id,function(err){ res.redirect('/') }) })