继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【金秋打卡】第10天 Node.js+Express+Koa2 开发Web Server博客 6-9

暮雩
关注TA
已关注
手记 65
粉丝 9
获赞 5

课程名称: 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

总结

  • nodejs 链接 mysql,如何执行 sql 语句
  • 根据 NODE_ENV 区分配置
  • 封装 exec 函数,api 使用 exec 操作数据库

课程收获:
博客的登录,有了一点了解
图片描述

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP