第四代Express框架koa简介

前端开发 作者: 2024-08-21 11:25:01
简介 熟悉Spring MVC的朋友应该都清楚Spring MVC是基于servlet的代码框架,这是最传统的web框架。然后在Spring5中引入了Spring WebFlux,这是基于reacti

简介

koa和express

koa使用介绍

const Koa = require('koa');
const app = module.exports = new Koa();

app.use(async function(ctx) {
  ctx.body = 'Hello World';
});

if (!module.parent) app.listen(3000);
const Koa = require('koa');
const app = new Koa();

app.use(async (ctx,next) => {
  await next();
  console.log('log3');
});

app.use(async (ctx,next) => {
  await next();
  console.log('log2');
});

app.use(async ctx => {
  console.log('log3');
});

app.listen(3000);
log1
log2
log3
constructor(options) {
    super();
    options = options || {};
    this.proxy = options.proxy || false;
    this.subdomainOffset = options.subdomainOffset || 2;
    this.proxyIpHeader = options.proxyIpHeader || 'X-Forwarded-For';
    this.maxIpsCount = options.maxIpsCount || 0;
    this.env = options.env || process.env.NODE_ENV || 'development';
    if (options.keys) this.keys = options.keys;
    this.middleware = [];
    this.context = Object.create(context);
    this.request = Object.create(request);
    this.response = Object.create(response);
    // util.inspect.custom support for node 6+
    /* istanbul ignore else */
    if (util.inspect.custom) {
      this[util.inspect.custom] = this.inspect;
    }
  }
  • app.env 默认值是NODE_ENV或者development
  • app.keys 为cookie签名的keys
app.keys = ['secret1','secret2'];
app.keys = new KeyGrip(['secret1','secret2'],'sha256');

ctx.cookies.set('name','jack',{ signed: true });
  • app.proxy 是否支持代理
  • app.subdomainOffset 表示子域名是从第几级开始的,这个参数决定了request.subdomains的返回结果,默认值为2
  • app.proxyIpHeader proxy ip header默认值是X-Forwarded-For
  • app.maxIpsCount 从proxy ip header读取的最大ip个数,默认值是0表示无限制。
const Koa = require('koa');
const app = new Koa({ proxy: true });
const Koa = require('koa');
const app = new Koa();
app.proxy = true;
const Koa = require('koa');
const app = new Koa();
app.listen(3000);
const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
const http = require('http');
const https = require('https');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
https.createServer(app.callback()).listen(3001);
async function responseTime(ctx,next) {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time',`${ms}ms`);
}

app.use(responseTime);
  • 给中间件起个名字:
function logger(name) {
  return async function logger(ctx,next) {
      console.log(name);
      await next();
  };    
}
  • 自定义中间件的扩展:
function logger(format) {
  format = format || ':method ":url"';

  return async function (ctx,next) {
    const str = format
      .replace(':method',ctx.method)
      .replace(':url',ctx.url);

    console.log(str);

    await next();
  };
}

app.use(logger());
app.use(logger(':method :url'));
  • 组合多个中间件:
const compose = require('koa-compose');
const Koa = require('koa');
const app = module.exports = new Koa();

// x-response-time

async function responseTime(ctx,next) {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  ctx.set('X-Response-Time',ms + 'ms');
}

// logger

async function logger(ctx,next) {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  if ('test' != process.env.NODE_ENV) {
    console.log('%s %s - %s',ctx.method,ctx.url,ms);
  }
}

// response

async function respond(ctx,next) {
  await next();
  if ('/' != ctx.url) return;
  ctx.body = 'Hello World';
}

// composed middleware

const all = compose([
  responseTime,logger,respond
]);

app.use(all);

if (!module.parent) app.listen(3000);

app.use(async (ctx,next) => {
  try {
    await next();
  } catch (err) {
    err.status = err.statusCode || err.status || 500;
    throw err;
  }
});

app.on('error',err => {
  log.error('server error',err)
});
app.on('error',(err,ctx) => {
  log.error('server error',err,ctx)
});
原创声明
本站部分文章基于互联网的整理,我们会把真正“有用/优质”的文章整理提供给各位开发者。本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
本文链接:http://www.jiecseo.com/news/show_66063.html