app.listen(...)

Koa 应用并非是一个 1-to-1 表征关系的 HTTP 服务器。 一个或多个Koa应用可以被挂载到一起组成一个包含单一 HTTP 服务器的大型应用群。

var koa = require('koa');
var app = koa();
app.listen();

app.listen(...) 实际上是以下代码的语法糖:

var http = require('http');
var koa = require('koa');
var app = koa();
http.createServer(app.callback()).listen();

这意味着您可以同时支持 HTTP 和 HTTPS,或者在多个端口监听同一个应用。

const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen();
http.createServer(app.callback()).listen();

app.callback()

返回一个适合 http.createServer() 方法的回调函数用来处理请求。 您也可以使用这个回调函数将您的app挂载在 Connect/Express 应用上。

/**
* Create HTTP server.
*/ var server = http.createServer(app.callback()); /**
* Listen on provided port, on all network interfaces.
*/ server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

app.use(function)

为应用添加指定的中间件,详情请看 Middleware

app.keys=

设置签名Cookie密钥,该密钥会被传递给 KeyGrip

当然,您也可以自己生成 KeyGrip 实例:

app.keys = ['im a newer secret', 'i like turtle'];
app.keys = new KeyGrip(['im a newer secret', 'i like turtle'], 'sha256');

在进行cookie签名时,只有设置 signed 为 true 的时候,才会使用密钥进行加密:

ctx.cookies.set('name', 'tobi', { signed: true });

app.context

app.context 是ctx中创造来的,你可以对通过app.context ctx增加属性。这是一个很有用的属性用来贯穿你的整个app.app.context is the prototype from which ctx is created from. You may add additional properties to ctx by editing app.context. This is useful for adding properties or methods to ctx to be used across your entire app, which may be more performant (no middleware) and/or easier (fewer require()s) at the expense of relying more on ctx, which could be considered an anti-pattern.

app.context.db = db();

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

错误处理

默认情况下Koa会将所有错误信息输出到 stderr,除非 NODE_ENV 是 "test"。为了实现自定义错误处理逻辑(比如 centralized logging),您可以添加 "error" 事件监听器。

app.on('error', function(err){
log.error('server error', err);
});

如果错误发生在 请求/响应 环节,并且其不能够响应客户端时,Contenxt 实例也会被传递到 error 事件监听器的回调函数里。

app.on('error', function(err, ctx){
log.error('server error', err, ctx);
});

当发生错误但仍能够响应客户端时(比如没有数据写到socket中),Koa会返回一个500错误(Internal Server Error)。

无论哪种情况,Koa都会生成一个应用级别的错误信息,以便实现日志记录等目的。

Context(上下文)

Koa Context 将 node 的 request 和 response 对象封装在一个单独的对象里面,其为编写 web 应用和 API 提供了很多有用的方法。

这些操作在 HTTP 服务器开发中经常使用,因此其被添加在上下文这一层,而不是更高层框架中,因此将迫使中间件需要重新实现这些常用方法。

context 在每个 request 请求中被创建,在中间件中作为接收器(receiver)来引用.

在KOA1.0中

app.use(function *(){
this; // is the Context
this.request; // is a koa Request
this.response; // is a koa Response
});

在KOA2.0中

app.use(async (ctx, next) => {
ctx; // is the Context
ctx.request; // is a koa Request
ctx.response; // is a koa Response
});

API

Context 详细的方法和访问器。

ctx.req

Node 的 request 对象。

ctx.res

Koa 不支持 直接调用底层 res 进行响应处理。请避免使用以下 node 属性:

res.statusCode,res.writeHead(),res.write(),res.end()

ctx.request

Koa 的 Request 对象。

ctx.response

Koa 的 Response 对象。

ctx.app

应用实例引用。

ctx.cookies.get(name, [options])

获得 cookie 中名为 name 的值,options 为可选参数:

  • 'signed': 如果为 true,表示请求时 cookie 需要进行签名。

注意:Koa 使用了 Express 的 cookies 模块,options 参数只是简单地直接进行传递。

ctx.cookies.set(name, value, [options])

设置 cookie 中名为 name 的值,options 为可选参数:

  • signed: 是否要做签名
  • expires: cookie 有效期时间
  • path: cookie 的路径,默认为 /'
  • domain: cookie 的域
  • secure: false 表示 cookie 通过 HTTP 协议发送,true 表示 cookie 通过 HTTPS 发送。
  • httpOnly: true 表示 cookie 只能通过 HTTP 协议发送

注意:Koa 使用了 Express 的 cookies 模块,options 参数只是简单地直接进行传递。

  if ( req.url == "/set" ) {
cookies
// set a regular cookie
.set( "unsigned", "foo", { httpOnly: false } ) // set a signed cookie
.set( "signed", "bar", { signed: true } ) // mimic a signed cookie, but with a bogus signature
.set( "tampered", "baz" )
.set( "tampered.sig", "bogus" ) res.writeHead( , { "Location": "/" } )
return res.end( "Now let's check." )
}

ctx.throw(msg, [status])

抛出包含 .status 属性的错误,默认为 500。该方法可以让 Koa 准确的响应处理状态。 Koa支持以下组合:

ctx.throw(403);
ctx.throw('name required', 400);
ctx.throw(400, 'name required');
ctx.throw('something exploded');

ctx.respond

为了避免使用 Koa 的内置响应处理功能,您可以直接赋值 this.repond = false;。如果您不想让 Koa 来帮助您处理 reponse,而是直接操作原生 res 对象,那么请使用这种方法。

注意: 这种方式是不被 Koa 支持的。其可能会破坏 Koa 中间件和 Koa 本身的一些功能。其只作为一种 hack 的方式,并只对那些想要在 Koa 方法和中间件中使用传统 fn(req, res) 方法的人来说会带来便利。

Request aliases

以下访问器和别名与 Request 等价:

  • ctx.header
  • ctx.method
  • ctx.method=
  • ctx.url
  • ctx.url=
  • ctx.originalUrl
  • 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 aliases

以下访问器和别名与 Response 等价:

  • ctx.body
  • ctx.body=
  • ctx.status
  • ctx.status=
  • ctx.length=
  • ctx.length
  • ctx.type=
  • ctx.type
  • ctx.headerSent
  • ctx.redirect()
  • ctx.attachment()
  • ctx.set()
  • ctx.remove()
  • ctx.lastModified=
  • ctx.etag=

KOA 学习(二)的更多相关文章

  1. emberjs学习二(ember-data和localstorage_adapter)

    emberjs学习二(ember-data和localstorage_adapter) 准备工作 首先我们加入ember-data和ember-localstorage-adapter两个依赖项,使用 ...

  2. ReactJS入门学习二

    ReactJS入门学习二 阅读目录 React的背景和基本原理 理解React.render() 什么是JSX? 为什么要使用JSX? JSX的语法 如何在JSX中如何使用事件 如何在JSX中如何使用 ...

  3. TweenMax动画库学习(二)

    目录            TweenMax动画库学习(一)            TweenMax动画库学习(二)            TweenMax动画库学习(三)            Tw ...

  4. Hbase深入学习(二) 安装hbase

    Hbase深入学习(二) 安装hbase This guidedescribes setup of a standalone hbase instance that uses the local fi ...

  5. Struts2框架学习(二) Action

    Struts2框架学习(二) Action Struts2框架中的Action类是一个单独的javabean对象.不像Struts1中还要去继承HttpServlet,耦合度减小了. 1,流程 拦截器 ...

  6. Python学习二:词典基础详解

    作者:NiceCui 本文谢绝转载,如需转载需征得作者本人同意,谢谢. 本文链接:http://www.cnblogs.com/NiceCui/p/7862377.html 邮箱:moyi@moyib ...

  7. Quartz学习--二 Hello Quartz! 和源码分析

    Quartz学习--二  Hello Quartz! 和源码分析 三.  Hello Quartz! 我会跟着 第一章 6.2 的图来 进行同步代码编写 简单入门示例: 创建一个新的java普通工程 ...

  8. SpringCloud学习(二):微服务入门实战项目搭建

    一.开始使用Spring Cloud实战微服务 1.SpringCloud是什么? 云计算的解决方案?不是 SpringCloud是一个在SpringBoot的基础上构建的一个快速构建分布式系统的工具 ...

  9. DjangoRestFramework学习二之序列化组件、视图组件 serializer modelserializer

      DjangoRestFramework学习二之序列化组件.视图组件   本节目录 一 序列化组件 二 视图组件 三 xxx 四 xxx 五 xxx 六 xxx 七 xxx 八 xxx 一 序列化组 ...

  10. Koa 学习笔记

    开始 就像官网上说的,一切框架都从一个"Hello World"开始,首先我们新建一个 package.json,内容尽量简单: { "name": " ...

随机推荐

  1. 6_3.springboot2.x数据整合Mybatis(注解和非注解)

    1.配置文件 pom.xml 导入mybatis提供的启动器 <dependency> <groupId>org.mybatis.spring.boot</groupId ...

  2. 华为-eNSP模拟器路由器无法正常启动一直显示“#”

    问题项如截图: 解决方案: 1. 打开自己电脑的控制面板 -->> 系统和安全 -->> Windows Defender防火墙 (运行应用通过Windows防火墙) 2 .找 ...

  3. eclipse 克隆 https 地址的 Git 仓库报错:cannot open git-upload-pack

    解决方法:Window >Preferences >Team>Git>User settings点击Add Entry设置key:http.sslVerify value:fa ...

  4. Amazon S3和EBS的区别

  5. Luogu P1039 侦探推理(模拟+枚举)

    P1039 侦探推理 题意 题目描述 明明同学最近迷上了侦探漫画<柯南>并沉醉于推理游戏之中,于是他召集了一群同学玩推理游戏.游戏的内容是这样的,明明的同学们先商量好由其中的一个人充当罪犯 ...

  6. datetime与timestamp相互转换

    select unix_timestamp('2019-12-05 12:26:35'); );

  7. github和gitlab仓库一起使用

    github是网络公有代码仓库,一般用于私人代码托管,而gitlab一般是企业搭建的内部代码仓库.工作期间,我们都会同时用到这两个仓库.可公司邮箱与个人邮箱是不同的,由此产生的 SSH key 也是不 ...

  8. React的PropTYpes

    React的PropTYpes和获取真实DOM 组件的属性可以接受任意值,字符串,对象,函数等等都可以.有时,我们需要一种机制,验证别人使用组件时,提供的参数是否符合要求. 组件类的PropsType ...

  9. php中Sessions

    PHP Sessions  Session 中文译名叫做“会话”,其本来的含义是指有始有终的一系列动作/消息. PHP session 变量用于存储关于用户会话(session)的信息,或者更改用户会 ...

  10. iOS开发CoreData的简单使用

    1.简介 CoreData是iOS5后,苹果提供的原生的用于对象化管理数据并且持久化的框架.iOS10苹果对CoreData进一步进行了封装,而且效率更高!相关类的简单介绍: NSManagedObj ...