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

运行效果

相关推荐
光影少年1 天前
RN的Fabric 渲染流程
运维·前端·javascript·react native·react.js·fabric
用户938515635071 天前
React Router 进阶:路由守卫、登录鉴权与状态传递
前端·javascript·全栈
kyriewen1 天前
我重写了自己用了两年的防抖节流Hook——发现里面藏着3个隐藏bug
前端·javascript·面试
漂流瓶jz1 天前
Webpack开发环境:观察模式/webpack-dev-server/HMR热更新
前端·javascript·webpack
小爬的老粉丝1 天前
Vue 3 文件预览生产排障:Worker/WASM 404、鉴权 Blob 与子路径
javascript·vue.js·wasm
亲亲小宝宝鸭1 天前
离谱架构系列——我在祖传代码里发现了【智子】
javascript
触底反弹1 天前
🚀 20 行代码手写前端路由 + React Router 核心 API 一篇搞定!
前端·javascript·react.js
布兰妮甜1 天前
Vue 状态管理选型:Pinia 完整实战,对比 Vuex,模块化持久化
前端·javascript·vue.js·pinia·vuex
labixiong1 天前
async/await 到底是不是 Generator 的语法糖?手写执行器,Babel 编译产物里藏着答案
前端·javascript·babel
windliang1 天前
Claude Code 源码分析(六):上下文的发现、注入与压缩
前端·javascript·人工智能