zoukankan      html  css  js  c++  java
  • koa.js基础概念

    koa

    Koa中最重要的概念:middleware, context, request, response

    const Koa = require('koa');
    const app = new Koa();
    
    // koa 中间件的写法与执行顺序
    app.use(async (ctx, next) => {
        // 1
        await next(); // 2
        console.log(`${ctx.method} ${ctx.url} ${ctx.response.get('X-Res-Time')}`); // 8
    });
    
    app.use(async (ctx, next) => {
        const start = Date.now(); // 3
        await next(); //4
        const ms = Date.now() - start; // 6
        ctx.response.set('X-Res-Time', `${ms}ms`); // 7
    });
    
    app.use(async ctx => {
        ctx.body = 'hello koajs'; // 5
    });
    
    app.listen(3000); // http.createServer(app.callback()).listen(3000);
    

    1.1 Context

    Context对象在每次请求的时候创建,它主要是对nodejs的requestresponse的封装

    app.use(async ctx => {
      ctx; // is the Context
      ctx.request; // is a Koa Request
      ctx.response; // is a Koa Response
      ctx.app; // is a Koa Application
      ctx.state.user = await User.find(id); 
      // ctx.state is the recommended namespace for passing information through middleware
      ctx.cookie; // cookie object
    });
    

    1.2 Request

    app.use(async ctx => {
      ctx.request; // is a Koa Request
      ctx.request.header; // request header
      ctx.request.method; // request method
      ctx.request.url;    // request url
      ctx.request.query; // convert 'color=blue&size=s' to {color:'blue', size: 's'}
      ctx.request.get(field); // get specific field in header
    });
    

    1.3 Response

    app.use(async ctx => {
      ctx.response; // is a Koa Request
      ctx.response.status = 200; 
      ctx.response.body = 'hello world';
      ctx.response.type = 'text/plain; charset=utf-8';
      ctx.set({
      'Etag': '1234',
      'Last-Modified': date
    });
      ctx.set('Cache-Control', 'no-cache');
      const etag = ctx.response.get('ETag'); // case-insensitive
    });
    
  • 相关阅读:
    Playwright安装及基本用法
    生成随机数、随机字符串
    xmind2testcase使用
    jmeter5.0二次开发环境搭建(IDEA)
    pytest配置文件pytest.ini
    pytest+allure2生成测试报告
    pytest生成html报告-使用pytest-html插件方式
    pytest一些简单参数
    pytest简单搭建和入门
    python3学习-元组
  • 原文地址:https://www.cnblogs.com/elimsc/p/15046720.html
Copyright © 2011-2022 走看看