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
    });
    
  • 相关阅读:
    Stacks And Queues
    Programming Assignment 5: Burrows–Wheeler Data Compression
    Data Compression
    Regular Expressions
    Programming Assignment 4: Boggle
    Oracle 查询表的索引包含的字段
    pycharm
    Java文件:追加内容到文本文件
    okhttp 使用response.body().string()获取到的数据是一堆乱码
    彻底解决unable to find valid certification path to requested target
  • 原文地址:https://www.cnblogs.com/elimsc/p/15046720.html
Copyright © 2011-2022 走看看