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

运行效果

相关推荐
心中有国也有家18 分钟前
AtomGit Flutter 鸿蒙客户端:Canvas 绘制进阶-路径、渐变与混合模式
android·javascript·flutter·华为·harmonyos
鹿目2 小时前
使用 Vant CLI 搭建 UI 组件库:从 H5 到小程序跨平台
前端·javascript
默_笙2 小时前
😭 我花了两小时找了一个数据结构 bug,才把"迷你 Cursor"跑起来,绝望(bushi)
前端·javascript
竹林8182 小时前
wagmi v2 监听合约事件踩坑记:从 `useContractEvent` 到 `watchContractEvent`,我重构了三版才搞定实时数据流
前端·javascript
xingcheng3 小时前
Vue 2 + JavaScript编码规范skill
javascript
Larcher3 小时前
从零实现一个可运行的 RAG - LangChain、内存向量库与检索增强生成
前端·javascript
mONESY3 小时前
Vue3流式调用大模型接口完整实践
javascript
qq_419854054 小时前
空间网格管理器
前端·javascript·html
李明卫杭州6 小时前
Vue2 与 Vue3 自定义指令详解:钩子变化、迁移指南与实战示例
前端·javascript·vue.js