Koajs-基于 Node.js 平台的下一代 web 开发框架

简介

        Koa 是一个新的 web 框架,由 Express 幕后的原班人马打造, 致力于成为 web 应用和 API 开发领域中的一个更小、更富有表现力、更健壮的基石。 通过利用 async 函数,Koa 帮你丢弃回调函数,并有力地增强错误处理。 Koa 并没有捆绑任何中间件, 而是提供了一套优雅的方法,帮助您快速而愉快地编写服务端应用程序。

安装

        Koa 依赖 node v7.6.0 或 ES2015及更高版本和 async 方法支持.

nvm install 7
npm i koa
node my-koa-app.js

Koa 应用程序是一个包含一组中间件函数的对象,它是按照类似堆栈的方式组织和执行的。

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

级联 

        Koa 中间件以更传统的方式级联,您可能习惯使用类似的工具 - 之前难以让用户友好地使用 node 的回调。然而,使用 async 功能,我们可以实现 “真实” 的中间件。对比 Connect 的实现,通过一系列功能直接传递控制,直到一个返回,Koa 调用“下游”,然后控制流回“上游”。

示例:

const Koa = require('koa');
const app = new Koa();

// logger

app.use(async (ctx, next) => {
  await next();
  const rt = ctx.response.get('X-Response-Time');
  console.log(`${ctx.method} ${ctx.url} - ${rt}`);
});

// x-response-time

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// response

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

 设置

应用程序设置是 app 实例上的属性,目前支持如下:

  • app.env 默认是 NODE_ENV 或 "development"
  • app.keys 签名的 cookie 密钥数组
  • app.proxy 当真正的代理头字段将被信任时
  • 忽略 .subdomains 的 app.subdomainOffset 偏移量,默认为 2
  • app.proxyIpHeader 代理 ip 消息头, 默认为 X-Forwarded-For
  • app.maxIpsCount 从代理 ip 消息头读取的最大 ips, 默认为 0 (代表无限)

app.context

app.context 是从其创建 ctx 的原型。您可以通过编辑 app.context 为 ctx 添加其他属性。这对于将 ctx 添加到整个应用程序中使用的属性或方法非常有用,这可能会更加有效(不需要中间件)和/或 更简单(更少的 require()),而更多地依赖于ctx,这可以被认为是一种反模式。

app.context.db = db();

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


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

app.use(function)

将给定的中间件方法添加到此应用程序。app.use() 返回 this, 因此可以链式表达.

app.use(someMiddleware)
app.use(someOtherMiddleware)
app.listen(3000)

// 还可以连缀写法 看个人喜好
app.use(someMiddleware)
  .use(someOtherMiddleware)
  .listen(3000)

 app.listen(...)

Koa 应用程序不是 HTTP 服务器的1对1展现。 可以将一个或多个 Koa 应用程序安装在一起以形成具有单个HTTP服务器的更大应用程序。

// Koa 应用程序不是 HTTP 服务器的1对1展现。 可以将一个或多个 Koa 应用程序安装在一起以形成具有单个HTTP服务器的更大应用程序。
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);

ctx.req 

Node 的 request 对象.

ctx.res 

Node 的 response 对象.

绕过 Koa 的 response 处理是 不被支持的. 应避免使用以下 node 属性:

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

使用中间件

Koa2 的核心思想是使用中间件来处理请求。中间件是一个函数,它接收两个参数:ctx 和 nextctx 是一个包含请求和响应信息的对象,next 是一个函数,它将控制权传递给下一个中间件。

const Koa = require('koa');
const app = new Koa();

app.use(async (ctx, next) => {
  console.log('1. This is the first middleware');
  await next();
  console.log('5. This is the fifth middleware');
});

app.use(async (ctx, next) => {
  console.log('2. This is the second middleware');
  await next();
  console.log('4. This is the fourth middleware');
});

app.use(async ctx => {
  console.log('3. This is the third middleware');
  ctx.body = 'Hello World';
});

app.listen(3000);

以上代码创建了三个中间件,它们按照顺序依次执行。当请求到达时,应用程序将输出以下内容:

1. This is the first middleware
2. This is the second middleware
3. This is the third middleware
4. This is the fourth middleware
5. This is the fifth middleware

使用路由

Koa2 可以使用第三方路由中间件来处理路由。以下是一个使用 koa-router 中间件的示例

const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();

router.get('/', async ctx => {
  ctx.body = 'Hello World';
});

router.get('/about', async ctx => {
  ctx.body = 'About Us';
});

app.use(router.routes());

app.listen(3000);

使用模板引擎

Koa2 可以使用第三方模板引擎中间件来渲染模板。以下是一个使用 koa-views 和 ejs 模板引擎的示例

 

const Koa = require('koa');
const views = require('koa-views');
const path = require('path');
const app = new Koa();

app.use(views(path.join(__dirname, '/views'), {
  extension: 'ejs'
}));

app.use(async ctx => {
  await ctx.render('index', {
    title: 'Koa2',
    message: 'Hello World'
  });
});

app.listen(3000);

以上就是对koa的一些基础了解和使用方法。

你可能感兴趣的:(koa,node.js,node.js)