koa-bodyparser解析通过post提交的参数
给ctx.request.body赋值,数据是通过Buffer格式传递,用toString()转为字符串。返回给前台
// 中间件:是一个函数,返回的是promise对象function bodyparser() {return async (ctx, next) => {await new Promise((resolve, reject) => {let arr = [];ctx.req.on("data", function (data) {arr.push(data);});ctx.req.on("end", () => {let res = Buffer.concat(arr).toString();ctx.request.body = res;resolve();});});await next();};}module.exports = bodyparser;
在end中处理不同的文件类型,主要处理上传文件类型。如果是数据直接返回,上传的是文件类型将文件写入到upload文件夹中。
ctx.req.on("end", () => {let type = ctx.get("Content-Type");// console.log(type);if (type.includes("multipart/form-data")) {let boundary = "--" + type.split("=")[1];// console.log(boundary);let buffer = Buffer.concat(arr);let lines = buffer.split(boundary).slice(1, -1);let obj = Object.create(null);lines.forEach((line) => {console.log(line.toString());let [head, content] = line.split("\r\n\r\n");head = head.toString();let key = head.match(/name="(.+?)"/)[1];// console.log(head);// 解析不同类型,文件以及数据if (head.includes("filename")) {// 上传的是文件类型let filename = uuid.v4();fs.writeFileSync(path.resolve(__dirname, "upload", filename),content.slice(0, -2),"utf8");obj[key] = filename;} else {// 正常数据流obj[key] = content.slice(0, -2).toString();}});ctx.request.body = obj;resolve();} else {resolve();}});
处理静态文件路径koa-static
在页面中引入的文件路径,解析成静态资源。可以直接在前端页面进行显示
const { createReadStream } = require("fs");const fs = require("fs").promises;const path = require("path");const mime = require("mime");function static(dirname) {return async (ctx, next) => {try {let filePath = path.join(dirname, ctx.path);let statObj = await fs.stat(filePath);if (statObj.isDirectory()) {filePath = path.join(filePath, "index.html");await fs.access(filePath);}ctx.set("Content-Type", mime.getType(filePath) + ";charset=UTF-8");ctx.body = createReadStream(filePath);} catch (e) {console.log(e);await next();}};}
