1.新增数据
依据后面的表和字段,当初咱们要在小程序端进行新增数据操作。
1). 首页,咱们先写新增数据接口,在/routes/anime.js
退出以下代码。新增数据个别用post
申请。因为波及到异步操作,所以用async
、await
进行操作。因为没做文件上传,所以,cover_url我就间接写了。图片是放在/public/images
上面的。
...const {mysql, mongodb} = require('access-db') //引入mysql操作方法,如果是mongodb,就引入对应的...//这里用postrouterAnime.post('/add', async function(req, res, next) { const {title, total, type} = req.body //小程序端上传的数据 try{ let tempRes = await mysql.set('anime', { title: title, cover_url: 'http://localhost:3000/images/1.webp', total: total, type: type, follows: 23 }) res.json(tempRes.data.insertId) }catch(err) { console.log('errrr', err) }});
req.body
就是post申请时,所带的参数。mysql.set
办法,就是新增数据,第一个参数就是数据表表名,第二个参数,就是要新增的内容。字段名必须和数据表外面字段名统一。此时的接口地址为:http://localhost:3000/anime/add 批改代码之后,记得重新启动后盾服务
2). 在微信小程序外面,增加一个绑定事件addOneData
index.wxml
<!--index.wxml--><view class="container"> <button bindtap="addOneData">新增数据</button></view>
index.js
...addOneData(){ wx.request({ url: 'http://localhost:3000/anime/add', method: 'POST', data: { title: '鬼灭之刃', total: 26, type: 1 }, success: (res) => { console.log('res', res) } })}...
最初,点击按钮,即可胜利增加数据了,留神关上不校验域名的设置。
2.获取一条数据
通过id,咱们能够间接获取某条数据的详情,获取数据。个别用get
在/router/anime.js
里,退出一个get申请。get
申请的参数,是在req.params
里。
//用 get申请routerAnime.get('/detail/:id', async function(req, res, next){ const {id} = req.params let temp = await mysql.get('anime', id) res.json(temp.data) // 以json类型返回数据})
写完下面代码后,记得重启服务器。
而后,在小程序端,咱们同样再绑定个事件,getOneData
... getOneData(){ wx.request({ url: 'http://localhost:3000/anime/detail/' + 5, method: 'GET', success: (res) => { console.log('获取一条数据:', res.data) } }) }, ...
能够看到,获取id为5的数据返回胜利
3.更新数据
同样的情理,/routes/anime.js
,增加如下。更新时,也要晓得更新的是哪条数据,所以,id也不少。更新数据,个别用put
办法。如下:
routerAnime.put('/update/:id', async function(req, res, next){ const {id} = req.params //url前面跟的参数 const {title} = req.body //小程序申请里,data里的参数 let temp = await mysql.update('anime', id, { title: title }) res.json(temp.data.changedRows)})
重启后盾服务器;而后,在小程序端,咱们同样再绑定个事件,updateOneData
...updateOneData(){ wx.request({ url: 'http://localhost:3000/anime/update/' + 5, method: 'PUT', data: { title: '新题目3' }, success: (res) => { console.log('更新数据:', res.data) } }) ...
能够看到,胜利更新的id为5的数据的title。
4.查寻数据
/routes/anime.js
,增加如下。查寻个别用get
办法。p0
为单个查寻条件,参数数组,第一个为字段,第二个为条件,第三个为内容。r
为执行查寻的规定。
如果咱们要查寻type
值等于1的数据,那么就能够如下这么写
routerAnime.get('/list/:page', async function(req, res, next){ const {page} = req.params let temp = await mysql.find('anime', { p0: ['type', '=', 1], r: 'p0' }) res.json(temp.data.objects)})
重启服务器,而后在小程序端,新增事件getList
getList(){ wx.request({ url: 'http://localhost:3000/anime/list/' + 1, method: 'GET', success: (res) => { console.log('查寻后果:', res.data) } })},
好了,到这里,基本上,你就能够开始写本人的小程序了,还是很简略吧,哈哈~