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('/')

})


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