课程名称: 2022全新 Node.js+Express+Koa2 开发Web Server博客
课程章节: 6-9 API对接mysql(登录)
课程讲师: 双越
课程内容:
修改项目 blog-1 文件夹。
对 博客的登录进行 修改
./src/controller/user.js
const { exec } = require("../db/mysql"); const loginCheck = (username, password) => { const sql = ` select username, realname from users where username='${username}' and password='${password}' `; return exec(sql).then((rows) => { return rows[0] || {}; }); }; module.exports = { loginCheck, };
./src/router/user.js
const { loginCheck } = require("../controller/user.js"); const { SuccessModel, ErrorModel } = require("../model/resModel.js"); // 登录相关接口 const handleUserRouter = (req, res) => { const method = req.method; // GET POST // 登录 if (method === "POST" && req.path === "/api/user/login") { const { username, password } = req.body; const result = loginCheck(username, password); return result.then((data) => { if (data?.username) { return new SuccessModel("这是登录的接口"); } return new ErrorModel("登录失败"); }); } }; module.exports = handleUserRouter;
app.js
const qs = require("qs"); // 博客相关接口 const handleBlogRouter = require("./src/router/blog.js"); // 登录相关接口 const handleUserRouter = require("./src/router/user.js"); // 用于处理 post data const getPostData = (req) => { return new Promise((resolve, reject) => { if (req.method !== "POST") { resolve({}); return; } if (req.headers["content-type"] !== "application/json") { resolve({}); return; } let postData = ""; req.on("data", (chunk) => { postData += chunk.toString(); }); req.on("end", () => { if (!postData) { resolve({}); return; } resolve(JSON.parse(postData)); }); }); }; const serverHandle = (req, res) => { // 设置返回格式 res.setHeader("Content-type", "application/json"); // 处理 path const url = req.url; // 获取路由 req.path = url.split("?")[0]; // 获取api // 解析 query req.query = qs.parse(url.split("?")[1]); // 处理post data getPostData(req).then((postData) => { // 保存 post 方式传递的数据 req.body = postData // 处理 user 路由 // const userData = handleUserRouter(req, res); // if (userData) { // res.end(JSON.stringify(userData)); // return; // } const userResult = handleUserRouter(req, res); if (userResult) { userResult.then((userData) => { res.end(JSON.stringify(userData)); }); return; } // 未命中路由,返回 404 // 设置返回头状态码为 404,并设置返回的数据类型为 text/plain(纯文本) res.writeHead(404, { "Content-type": "text/plain" }); res.write("404 Not Found\n"); res.end(); }); }; module.exports = serverHandle; // process.env.NODE_ENV
总结
课程收获:
博客的登录,有了一点了解