课程名称: 新版 Node.js+Express+Koa2 开发Web Server博客
课程章节: 10-7 express 开发博客项目-初始化环境
课程讲师: 双越
课程内容:
安装插件 mysql,xss
npm i mysql xss -S
mysql,controller,resModel 相关代码可以复用
初始化路由
代码演示
使用 express blog-erpress
生成express 代码。
安装 nodemon、cross-env、mysql、xss 并修改 package代码
npm i nodemon cross-env -D // && npm i mysql xss -S
// package.js { "name": "blog-express", "version": "0.0.0", "private": true, "scripts": { "start": "node ./bin/www", "dev": "cross-env NODE_ENV=dev nodemon ./bin/www" }, "dependencies": { "cookie-parser": "~1.4.4", "debug": "~2.6.9", "express": "~4.16.1", "http-errors": "~1.6.3", "jade": "~1.11.0", "morgan": "~1.9.1", "mysql": "^2.18.1", "xss": "^1.0.14" }, "devDependencies": { "cross-env": "^7.0.3", "nodemon": "^2.0.20" } }
删除public、views 文件相关的代码,删除路由文件,创建自己的路由文件 blog.js、user.js,并引入注册。
拷贝以前的 config、controller、db、model、utils/crype.js 文件过来
/* *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"); // 路由 router.get("/list", (req, res, next) => { let author = req.query.author || ""; const keyword = req.query.keyword || ""; // if (req.query.isadmin) { // // 管理员界面 // const loginCheckResult = loginChect(req); // if (loginCheckResult) { // // 未登录 // return loginCheckResult; // } // // 强制查询自己的博客 // author = req.session.username; // } // 获取数据库中的博客列表 const result = getList(author, keyword); // 返回 promise return result.then((listData) => { res.json(new SuccessModel(listData, "这是获取博客列表的接口")); }); }); router.get("/detail", function (req, res, next) { res.json({ errno: 0, data: "ok", }); }); module.exports = router;
/* *user.js */ const express = require("express"); const router = express.Router(); router.post("/login", function (req, res, next) { const { username, password } = req.body; res.json({ errno: 0, data: { username, password, }, }); }); module.exports = router;
/* *app.js */ const createError = require("http-errors"); const express = require("express"); const cookieParser = require("cookie-parser"); const logger = require("morgan"); // 引入博客路由 const blogRouter = require("./routes/blog"); // 引入用户路由 const userRouter = require("./routes/user"); // 主程序 const app = express(); // 中间件 app.use(logger("dev")); app.use(express.json()); app.use(express.urlencoded({ extended: false })); app.use(cookieParser()); // 路由 app.use("/api/blog", blogRouter); app.use("/api/user", userRouter); // 处理404 app.use(function (req, res, next) { next(createError(404)); }); // 处理错误 app.use(function (err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get("env") === "development" ? err : {}; // 返回错误信息 res.status(err.status || 500); res.json({ error: err }); }); module.exports = app;
项目最终结构
课程收获: