课程名称: 2022全新 Node.js+Express+Koa2 开发Web Server博客
课程章节: 6-7 API对接mysql(博客详情和新建)
课程讲师: 双越
课程内容:
修改项目 blog-1 文件夹。
对 博客详情 和 新建 进行修改
./src/controller/blog.js
/*
数据层
*/
const { exec } = require("../db/mysql");
// 获取博客详情
const getDetail = (id) => {
const sql = `select * from blogs where id='${id}'`;
return exec(sql).then((rows) => {
// 返回一个对象
return rows[0];
});
};
// 新建一篇博客
const newBlog = (blogData = {}) => {
// blogData 是一个博客对象,包含 title content author 属性
const title = blogData.title;
const content = blogData.content;
const author = blogData.author;
const createTime = Date.now();
const sql = `
insert into blogs (title, content, createTime, author )
value ('${title}', '${content}', ${createTime}, '${author}')
`;
return exec(sql).then((insertData) => {
// console.log("insertData is", insertData);
return {
id: insertData.insertId,
};
});
};
module.exports = {
getDetail,
newBlog,
};
./src/router/blog.js
const {
getDetail,
newBlog,
} = 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 == "GET" && req.path === "/api/blog/detail") {
/* const data = getDetail(id);
return new SuccessModel(data, "这是获取博客详情的接口"); */
const result = getDetail(id);
return result.then((data) => {
return new SuccessModel(data, "这是获取博客详情的接口");
});
}
// 新建一篇博客
if (method == "POST" && req.path === "/api/blog/new") {
/* const data = newBlog(req.body);
return new SuccessModel(data, "这是新建博客的接口"); */
// 假数据,在开发登录时再改成真数据
req.body.author = "zhangsan";
const result = newBlog(req.body);
return result.then((data) => {
return new SuccessModel(data, "这是新建博客的接口");
});
}
};
module.exports = handleBlogRouter;
课程收获:
从mysql获取博客详情和新建博客,有一定的了解