【Part3】用JS写一个Blog (node + vue + mongoDB)

发布时间:2019-05-29 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了【Part3】用JS写一个Blog (node + vue + mongoDB)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

【Part1】用JS写一个Blog (node + vue + mongoDB)
【Part2】用JS写一个Blog (node + vue + mongoDB)

上一节我们把数据库连接成功了,这节我准备写关于文章的数据接口(增 删 改 查)
上次说到接口都在routers文件夹里面写,打开post.js文件,首先引入文章的模型

let postModel = require('../models/post')

新增文章API

//新增文章
router.post('/create', (req, res, next) => {
  let title = req.body.title
  let content = req.body.content

  let post = new postModel()
  post.title = title
  post.content = content
  post.save((err, doc) => {  // save方法保存数据到数据库
    if (err) {
      next(err)    // 如果出现错误,直接把错误next进express的错误中枢处理
    } else {
      res.json({    //储存成功后,返回给客户端一个json
        status: 0,
        msg: '创建成功'
      })
    }
  })
})

查询文章列表API

router.get('/postslist', (req, res, next) => {
  postModel.find({}, (err, posts) => {   //find查询方法第一个参数是查询条件,如果为空,则查询所有的,后面是一个回调,回调中第一个参数是错误,第二个参数是查询的结果,在这里为一个数组
    if (err) {
      next(err)
    } else {
      res.json({
        status: 0,
        list: posts
      })
    }
  })
})

更改文章内容API

router.post('/update', (req, res, next) => {
  let id = req.body.id      //拿到客户端传递过来的文章id,根据id来查找到该文章
  let title = req.body.title
  let content = req.body.content

  postModel.findOneAndUpdate({_id: id}, {title, content}, err => {
    if (err) {
      next(err)
    } else {
      res.json({
        status: 0,
        msg: '更新成功'
      })
    }
  })
})

删除文章API

router.get('/delete', (req, res, next) => {
  let id = req.query.id

  postModel.remove({_id: id}, err => {
    if (err) {
      next(err)
    } else {
      res.json({
        status: 0,
        msg: '删除成功'
      })
    }
  })
})

然后最后把接口暴露出去
module.exports = router

脚本宝典总结

以上是脚本宝典为你收集整理的【Part3】用JS写一个Blog (node + vue + mongoDB)全部内容,希望文章能够帮你解决【Part3】用JS写一个Blog (node + vue + mongoDB)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:Vue