课程名称: 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 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦