koa创建的app的属性及方法

黑色大本笔记:

回顾: 开始你的第一个Koa应用程序 hello world

app.listen(…)

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);

//配置一个应用程序同时作为HTTP或HTTPS等多个地址
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);

app.callback()

返回适用于 http.createServer() 方法的回调函数来处理请求。你也可以使用此回调函数将 koa 应用程序挂载到 Connect/Express 应用程序中。

app.use(function)

将给定的中间件方法添加到此应用程序。

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');

这些密钥可以倒换,并在使用 { signed: true } 参数签名 Cookie 时使用。

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

app.context

app.context 是从其创建 ctx 的原型。您可以通过编辑 app.contextctx 添加其他属性。

例如,要从 ctx 添加对数据库的引用:

app.context.db = db();

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

注意:

ctx 上的许多属性都是使用 gettersetterObject.defineProperty() 定义的。你只能通过在 app.context 上使用 Object.defineProperty() 来编辑这些属性(不推荐)。查阅 defineProperty
安装的应用程序目前使用其父级的 ctx 和设置。 因此,安装的应用程序只是一组中间件。

app.on 错误处理

默认情况下,将所有错误输出到 stderr,除非 app.silent 为 true。 当 err.status 是 404 或 err.expose 是 true 时默认错误处理程序也不会输出错误。 要执行自定义错误处理逻辑,如集中式日志记录,您可以添加一个 “error” 事件侦听器

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

//如果 req/res 期间出现错误,并且 _无法_ 响应客户端,
//Context实例仍然被传递:
app.on('error', (err, ctx) => {
  log.error('server error', err, ctx)
});

当发生错误并且仍然可以响应客户端时,也没有数据被写入 socket 中,Koa 将用一个 500 “内部服务器错误” 进行适当的响应。
在任一情况下,为了记录目的,都会发出应用级 “错误”。

果然电子文档的看着很顺眼,主要是比我写的字好看

发布了20 篇原创文章 · 获赞 38 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/jiamiao66/article/details/100766271
koa