一线大厂高级前端编写,前端初中阶面试题,帮助初学者应聘,需要联系微信:javadudu

koa使用教程

koa使用教程

环境

安装 koa2

npm install koa-generator -g
koa2 koa2-test

添加 dev 环境

npm install cross-env --save-dev

package.json

{
	"scripts": {
    "dev":"cross-env NODE_ENV=dev ./node_modules/.bin/nodemon bin/www"
  }
}

中间件

const Koa = require("koa");
const app = new Koa();

// logger

app.use(async (ctx, next) => {
  await next();
  const rt = ctx.response.get("X-Response-Time");
  console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});

// x-response-time

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set("X-Response-Time", `${ms}ms`);
});

// response

app.use(async (ctx) => {
  ctx.body = "Hello World";
});

app.listen(3000);

原理

  • app.use 用来注册中间件,先收集起来
  • 实现 next 机制,即上一个通过 next 触发下一个
  • 不涉及 method 和 path 的判断

实现

const http = require("http");

// 组合中间件
function compose(middlewareList) {
  return function (ctx) {
    function dispatch(i) {
      const fn = middlewareList[i];
      try {
        return Promise.resolve(
          fn(ctx, dispatch.bind(null, i + 1)) // promise
        );
      } catch (err) {
        return Promise.reject(err);
      }
    }
    return dispatch(0);
  };
}

class LikeKoa2 {
  constructor() {
    this.middlewareList = [];
  }

  use(fn) {
    this.middlewareList.push(fn);
    return this;
  }

  createContext(req, res) {
    const ctx = {
      req,
      res,
    };
    ctx.query = req.query;
    return ctx;
  }

  handleRequest(ctx, fn) {
    return fn(ctx);
  }

  callback() {
    const fn = compose(this.middlewareList);

    return (req, res) => {
      const ctx = this.createContext(req, res);
      return this.handleRequest(ctx, fn);
    };
  }

  listen(...args) {
    const server = http.createServer(this.callback());
    server.listen(...args);
  }
}

module.exports = LikeKoa2;

session

npm install koa-generic-session --save

app.js

const session = require("koa-generic-session");

// session配置
app.keys = ["abcdefg"];
app.use(
  session({
    // 配置cookie
    cookie: {
      path: "/",
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000,
    },
  })
);

redis

npm install redis koa-redis --save

app.js

const session = require("koa-generic-session");
const redisStore = require("koa-redis");

app.use(
  session({
    cookie: {
      path: "/",
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000,
    },
    // 配置redis
    store: redisStore({
      all: "127.0.0.1:6379",
    }),
  })
);

logs

npm install koa-morgan --save

app.js

const fs = require("fs");
const path = require("path");
const morgan = require("koa-morgan");

const ENV = process.env.NODE_ENV;
if (ENV !== "production") {
  // 开发环境
  app.use(morgan("dev"));
} else {
  // 生产环境
  const logFileName = path.join(__dirname, "logs", "access.log");
  const writeStream = fs.createWriteStream(logFileName, {
    flags: "a",
  });
  app.use(
    morgan("combined", {
      stream: writeStream,
    })
  );
}
(0)
上一篇 2020年9月28日 下午11:26
下一篇 2020年9月30日 上午11:50

相关推荐

发表评论

登录后才能评论