美文网首页KOA
6.1KOA 应用上下文 Context

6.1KOA 应用上下文 Context

作者: 帶頭二哥 | 来源:发表于2020-01-06 01:55 被阅读0次

    应用上下文 Context

    • Koa Context 将 node 的 request 和 response 对象封装在一起

    • 每个请求都将创建一个 Context,并在中间件中作为接收器引用,或者 ctx 标识符,如以下代码片段所示:

    app.use(async (ctx,next) => {
      ctx; // 这是 Context
      ctx.req // Node 的 request 对象
      ctx.res // Node 的 response 对象
    
      // 这是 koa Request 对象内部封装 node request 对象,ctx.request.req 就是 node 的 request 对象
      ctx.request; 
    
      // 这是 koa Response 对象内部封装 node response 对象,ctx.request.res 就是 node 的 response 对象
      ctx.response;
    
      ctx.app // 应用程序实例引用
      
      /*
        ctx.throw(400, 'name required')
      等价于
        const err = new Error('name required');
        err.status = 400;
        err.expose = true;
        throw err;
      */
      ctx.throw([status], [msg], [properties]) // 抛出异常
      
      ctx.cookies.get(name, [options]) // 获取 cookies
      ctx.cookies.set(name, value, [options]) // 设置 cookies
      ...
    });
    
    Request 别名
    • ctx.header
    • ctx.headers
    • ctx.method
    • ctx.method=
    • ctx.url
    • ctx.url=
    • ctx.originalUrl
    • ctx.origin
    • ctx.href
    • ctx.path
    • ctx.path=
    • ctx.query
    • ctx.query=
    • ctx.querystring
    • ctx.querystring=
    • ctx.host
    • ctx.hostname
    • ctx.fresh
    • ctx.stale
    • ctx.socket
    • ctx.protocol
    • ctx.secure
    • ctx.ip
    • ctx.ips
    • ctx.subdomains
    • ctx.is()
    • ctx.accepts()
    • ctx.acceptsEncodings()
    • ctx.acceptsCharsets()
    • ctx.acceptsLanguages()
    • ctx.get()
    Response 别名
    • ctx.body
    • ctx.body=
    • ctx.status
    • ctx.status=
    • ctx.message
    • ctx.message=
    • ctx.length=
    • ctx.length
    • ctx.type=
    • ctx.type
    • ctx.headerSent
    • ctx.redirect()
    • ctx.attachment()
    • ctx.set()
    • ctx.append()
    • ctx.remove()
    • ctx.lastModified=
    • ctx.etag=

    相关文章

      网友评论

        本文标题:6.1KOA 应用上下文 Context

        本文链接:https://www.haomeiwen.com/subject/bnrhactx.html