课程名称: 新版 Node.js+Express+Koa2 开发Web Server博客
课程章节: 10-12 开发路由
课程讲师: 双越
routes/blog.js
const express = require("express");
const router = express.Router();
const {
getList,
getDetail,
newBlog,
updateBlog,
delBlog,
} = require("../controller/blog.js");
const { SuccessModel, ErrorModel } = require("../model/resModel.js");
const loginCheck = require("../middleware/loginCheck.js");
// 博客列表
router.get("/list", (req, res, next) => {
let author = req.query.author || "";
const keyword = req.query.keyword || "";
if (req.query.isadmin) {
// 管理员界面
if (req.session.username == null) {
// 未登录
res.json(new ErrorModel("未登录"));
return;
}
// 强制查询自己的博客
author = req.session.username;
}
// 获取数据库中的博客列表
const result = getList(author, keyword);
// 返回 promise
return result.then((listData) => {
res.json(new SuccessModel(listData, "这是获取博客列表的接口"));
});
});
// 博客详情
router.get("/detail", (req, res, next) => {
const result = getDetail(req.query.id);
return result.then((data) => {
res.json(new SuccessModel(data, "这是获取博客详情的接口"));
});
});
// 新建一篇博客
router.post("/new", loginCheck, (req, res, next) => {
req.body.author = req.session.username;
const result = newBlog(req.body);
return result.then((data) => {
res.json(new SuccessModel(data, "这是新建博客的接口"));
});
});
// 更新一篇博客
router.post("/update", loginCheck, (req, res, next) => {
const result = updateBlog(req.query.id, req.body);
return result.then((val) => {
// 判断是否成功
if (val) {
res.json(new SuccessModel("这是更新博客的接口"));
} else {
res.json(new ErrorModel("更新博客失败"));
}
});
});
// 删除一篇博客
router.post("/del", loginCheck, (req, res, next) => {
const author = req.session.username;
let result = delBlog(req.query.id, author);
return result.then((val) => {
// 判断是否成功
if (val) {
res.json(new SuccessModel("这是删除博客的接口"));
} else {
res.json(new ErrorModel("删除博客失败"));
}
});
});
module.exports = router;
课程内容:
- 对博客路由的重构