node epress 讀取,寫入,修改本地數據。模擬數據庫的增刪改查

1.開發模擬的小型數據庫
1.1新建目錄,自動生產 epress() ../node_modules/.bin/express -e
1.2再安裝cnpm i 安裝依賴得到庫
2 創建一個db.js 作爲小型的數據庫 
2.1 創建一個數組 獲取本地的文件
const repos=require('./data');
文件的持久化,保存在本地
const  fs =require('fs') ;
創建一個對象 對象具有增刪改查的功能。
__dirname表示當前目錄下 寫入數據該是json字符串
module.exports={
//寫入數據
 store(){
fs.writeSync(__dirname+'/data.json',JSON.stringify(repos));
},
//獲取一條數據
get(index){
return repos[index]
},
//獲取所有數據
get list(){
return repos;
},
//添加數據
add(article){
repos.push((article))
this.store()
},
//刪除數據
del(index){
 repos.splice(index,1)
this.store()
},
//更改
update(index,newArticle){
repos.splice(index,1,newArticle)
this.store()
}
}
代碼:
const repos=require('./data');
const  fs =require('fs') ;


module.exports={
store(){
fs.writeFileSync(__dirname+'/data.json',JSON.stringify(repos));
},
get(index){
return repos[index]
},
get list(){
return repos;
},
add(article){
repos.push((article))
this.store()
},
del(index){
 repos.splice(index,1)
this.store()
},
update(index,newArticle){
 repos.splice(index,1,newArticle)
this.store()
}
}
創建測試文件夾 對數據進行讀取,寫入,並且保存在本地
da-test
‘use strict’
let db =require('../db')
db.add({name:'1223'})




3.通過頁面進行文章列表添加
1.在頁面寫一個表單
<form action="/add" method="post">
  <label>標題
  <input type="text" name="title">
 
  </label>
  <input type="submit" value="添加">
  </form>
路由對於的添加函數
req.body表單裏面穿過來的值 表單請求的地址:/add,方式post ,發送的數據格式是form data,
不會在url進行顯示,res.redirect('/')重定向頁面
 app.post('/add',function (req,res) {
db.add({name:req.body.title})
res.redirect('/')
})


4.刪除列表中的一行 a標籤是發送請求用get 自後臺用query來獲取?參數後的信息


<a href="del?/index=<%=index  %>">刪除</a>
修改appjs 
app.get('/del',function(req,res){
let indexshow=req.query.index;
db.del(indexshow);
res.redirect('/')
})
一定要重新運行


更改功能  
1.首頁顯示活動需要更改的值 點擊按鈕向後臺請求,通過id,像後臺請求原始的數據
頁面: 
<a onclick="edit(<%=index %>)">更改</a>
<script type="text/javascript">
  function edit(index) {
 
  $.get("get/"+index,function(res){

           $("#title").val(res.name)
            $("#index").val(index)


  })
  }
  </script>


2.修改之後的提交,也是通過id,修改值,像後臺提交請求
app.post('/update',function (req,res) {
let index=req.body.index;
let article={name:req.body.title};
db.update(index,article)
res.redirect('/')

})


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章