为了账号安全,请及时绑定邮箱和手机立即绑定

【金秋打卡】第9天 Node.js+Express+Koa2 开发Web Server博客 6-8

标签:
征文 活动

课程名称: 2022全新 Node.js+Express+Koa2 开发Web Server博客

课程章节: 6-8 API对接mysql(博客更新和删除)

课程讲师: 双越

课程内容:
修改项目 blog-1 文件夹。
对 博客更新 和 删除进行修改
./src/controller/blog.js

/* 
  数据层
*/
const { exec } = require("../db/mysql");


// 更新一篇博客
const updateBlog = (id, blogData = {}) => {
  // id 就是要更新博客的id
  // blogData 是一个博客对象,包含 title content 属性
  const title = blogData.title;
  const content = blogData.content;

  const sql = `
      update blogs set title='${title}', content='${content}' where id=${id}
    `;

  return exec(sql).then((updateData) => {
    // console.log("updateData is", updateData);
    if (updateData.affectedRows > 0) {
      return true;
    }
    return false;
  });
};

// 删除一篇博客
const delBlog = (id, author) => {
  // id 就是要删除博客的id
  const sql = `delete from blogs where id=${id} and author='${author}'`;

  return exec(sql).then((delData) => {
    // console.log("delData is", delData);
    if (delData.affectedRows > 0) {
      return true;
    }

    return false;
  });
};

module.exports = {

  updateBlog,
  delBlog,
};


./src/router/blog.js

const {
  updateBlog,
  delBlog,
} = require("../controller/blog.js");

const { SuccessModel, ErrorModel } = require("../model/resModel.js");

// 博客相关接口
const handleBlogRouter = (req, res) => {
  const method = req.method; // GET POST
  const id = req.query.id;


  // 更新一篇博客
  if (method == "POST" && req.path === "/api/blog/update") {
    const result = updateBlog(id, req.body);

    return result.then((val) => {
      // 判断是否成功
      if (val) {
        return new SuccessModel("这是更新博客的接口");
      } else {
        return new ErrorModel("更新博客失败");
      }
    });
  }

  // 删除一篇博客
  if (method == "POST" && req.path === "/api/blog/del") {
    // 假数据,在开发登录时再改成真数据
    const author = "zhangsan";
    let result = delBlog(id, author);

    return result.then((val) => {
      // 判断是否成功
      if (val) {
        return new SuccessModel("这是删除博客的接口");
      } else {
        return new ErrorModel("删除博客失败");
      }
    });
  }
};

module.exports = handleBlogRouter;

课程收获:
更新mysql博客数据和删除博客数据,有一定的了解
图片描述

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
Web前端工程师
手记
粉丝
10
获赞与收藏
5

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消