koa-bodyparser解析通过post提交的参数

给ctx.request.body赋值,数据是通过Buffer格式传递,用toString()转为字符串。返回给前台

  1. // 中间件:是一个函数,返回的是promise对象
  2. function bodyparser() {
  3. return async (ctx, next) => {
  4. await new Promise((resolve, reject) => {
  5. let arr = [];
  6. ctx.req.on("data", function (data) {
  7. arr.push(data);
  8. });
  9. ctx.req.on("end", () => {
  10. let res = Buffer.concat(arr).toString();
  11. ctx.request.body = res;
  12. resolve();
  13. });
  14. });
  15. await next();
  16. };
  17. }
  18. module.exports = bodyparser;

在end中处理不同的文件类型,主要处理上传文件类型。如果是数据直接返回,上传的是文件类型将文件写入到upload文件夹中。

  1. ctx.req.on("end", () => {
  2. let type = ctx.get("Content-Type");
  3. // console.log(type);
  4. if (type.includes("multipart/form-data")) {
  5. let boundary = "--" + type.split("=")[1];
  6. // console.log(boundary);
  7. let buffer = Buffer.concat(arr);
  8. let lines = buffer.split(boundary).slice(1, -1);
  9. let obj = Object.create(null);
  10. lines.forEach((line) => {
  11. console.log(line.toString());
  12. let [head, content] = line.split("\r\n\r\n");
  13. head = head.toString();
  14. let key = head.match(/name="(.+?)"/)[1];
  15. // console.log(head);
  16. // 解析不同类型,文件以及数据
  17. if (head.includes("filename")) {
  18. // 上传的是文件类型
  19. let filename = uuid.v4();
  20. fs.writeFileSync(
  21. path.resolve(__dirname, "upload", filename),
  22. content.slice(0, -2),
  23. "utf8"
  24. );
  25. obj[key] = filename;
  26. } else {
  27. // 正常数据流
  28. obj[key] = content.slice(0, -2).toString();
  29. }
  30. });
  31. ctx.request.body = obj;
  32. resolve();
  33. } else {
  34. resolve();
  35. }
  36. });

处理静态文件路径koa-static

在页面中引入的文件路径,解析成静态资源。可以直接在前端页面进行显示

  1. const { createReadStream } = require("fs");
  2. const fs = require("fs").promises;
  3. const path = require("path");
  4. const mime = require("mime");
  5. function static(dirname) {
  6. return async (ctx, next) => {
  7. try {
  8. let filePath = path.join(dirname, ctx.path);
  9. let statObj = await fs.stat(filePath);
  10. if (statObj.isDirectory()) {
  11. filePath = path.join(filePath, "index.html");
  12. await fs.access(filePath);
  13. }
  14. ctx.set("Content-Type", mime.getType(filePath) + ";charset=UTF-8");
  15. ctx.body = createReadStream(filePath);
  16. } catch (e) {
  17. console.log(e);
  18. await next();
  19. }
  20. };
  21. }