Koa.js 入门手册:洋葱模型插件机制详解以及常用中间件

前言

Nodejs 提供了 http 能力,我们通过如下代码可以快速创建一个http server服务

javascript 复制代码
const http = require('http');

http
  .createServer((req, res) => {
    res.write('hello\n');
    res.end();
  })
  .listen(3000);

使用nodejs提供的原生能力启动一个http server并不麻烦,但是拓展额外的能力就比较麻烦,比如支持路由router,静态资源,页面模板等。

插件机制是目前非常流行的拓展能力的设计方式,Koa框架是基于插件机制封装出来的一个Node HTTP框架,我将简单记录一下Koa的插件机制以及丰富的插件。

快速启动

javascript 复制代码
// app.js
const Koa = require('koa');
const app = new Koa();

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

app.listen(9999,()=>{
    console.log('App start on port: 9999')
});
json 复制代码
// package.json
{
 "scripts": {
    "dev": "node app.js"
  }
}

中间件Middleware(洋葱模型)

通过 Koa.use 将中间件注册到 koa应用中,中间件可以注册N个

我们可以通过插件机制个性化功能,提供给别人复用
中间件格式 async (ctx,next)=>{}

  • ctx => context对象,包含request,response对象,我们可以通过ctx来处理自己的业务需求
  • next ,promise对象,可以通过await next(),让程序执行下一个中间件,执行完后再执行当前中间件next下面的逻辑
javascript 复制代码
const Koa = require('koa');

const app = new Koa();

app.use(async(ctx,next)=>{
  console.log('middleware one in')
  await next();
  console.log('middleware one out')
})

app.use(async(ctx,next)=>{
  console.log('middleware two in')
  await next();
  console.log('middleware two out')
})

app.use(async(ctx,next)=>{
  console.log('middleware three in')
  await next();
  console.log('middleware three out')
})

app.listen(9999, () => {
  console.log("app started! port:9999");
});

运行结果

javascript 复制代码
middleware one in
middleware two in
middleware three in
middleware three out
middleware two out
middleware one out

中间件运行过程

常用中间件

Koa Router

作为一个HTTP server,处理不同path的请求是最常见的问题,koa router就是专门处理路由分发的中间件

主程序

javascript 复制代码
const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();

router.get('/',async(ctx)=>{
  ctx.type = 'html';
  ctx.body = '<h1>hello world!</h1>';
})

app.use(router.routes());
app.use(router.allowedMethods())

app.listen(9999, () => {
  console.log("app started! port:9999");
});

运行结果

属性简介

Router实例上提供了http的多种请求方式 get post put delete等等。router的请求方法会接受两个参数,第一个参数是匹配的请求的路径 path,第二个参数是处理逻辑的函数。

Router的 routes,allowedMethods方法返回参数,是koa实例接受中间件格式。

Koa View

页面渲染器,支持多种成熟的模版解析引擎。

shell 复制代码
npm add koa-view ejs

主程序代码

javascript 复制代码
//app.js
const Koa = require('koa');
const Router = require('koa-router');
const views = require('koa-views');

const app = new Koa();
const router = new Router();

app.use(views(__dirname + '/views', {
  map: {
    html: 'ejs'
  }
}))



router.get('/home',async(ctx)=>{
  await ctx.render('home',{words:'欢迎你'})
})

app.use(router.routes());
app.use(router.allowedMethods())

app.listen(9999, () => {
  console.log("app started! port:9999");
});

html模版

html 复制代码
// views/home.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>乐闻世界</title>
</head>

<body>
    乐闻世界<%= words %>
</body>

</html>

运行效果

Koa Static

koa 支持静态资源的请求

相关依赖

shell 复制代码
yarn add koa-static

主程序

javascript 复制代码
const Koa = require('koa');
const static = require('koa-static');

const app = new Koa();

app.use(static(__dirname + '/statics'))

app.listen(9999, () => {
  console.log("app started! port:9999");
});

运行效果

相关推荐
_Kayo_1 天前
TypeScript 学习笔记2
前端·javascript·typescript
前端 贾公子1 天前
Eruda:移动端网页调试利器
前端·javascript·vue.js
Hashan1 天前
Elpis:抽离业务代码,发布NPM包
前端·javascript·vue.js
用户47949283569151 天前
0.1加0.2为什么不等于0.3-答不上来的都挂了
前端·javascript·面试
rit84324991 天前
C#实现的远程控制系统
前端·javascript·c#
南山安1 天前
React学习:Vite+React 基础架构分析
javascript·react.js·面试
JS_GGbond1 天前
JavaScript事件循环:餐厅里的“宏任务”与“微任务”
开发语言·javascript·ecmascript
CodeCraft Studio1 天前
JavaScript图表库 DHTMLX Diagram 6.1 重磅发布:全新PERT模式上线,项目可视化能力再升级!
开发语言·javascript·ecmascript·dhtmlx·图表开发·diagram·javascript图表库
shuaijie05181 天前
当表格数据量过大的时候,如何使用不分页进行展示
javascript·vue.js·ecmascript
How_doyou_do1 天前
常见的设计模式
前端·javascript·设计模式