博客
关于我
nodejs koa入门指引
阅读量:128 次
发布时间:2019-02-27

本文共 5534 字,大约阅读时间需要 18 分钟。

Koa框架入门与实践指南

环境配置

  • 操作系统:macOS Catalina 10.15.4
  • Node.js:v10.20.0(ES2015及以上及async函数支持)
  • npm:6.14.4
  • Koa:2.11.0

1. 介绍

Koa 由 Express 团队设计,是 Express 的下一代Web框架,旨在为 Web 应用和 API 开发提供更小、更灵活、更稳健的基础。通过利用异步功能,Koa 消除了回调的痛点,提升了错误处理能力,避免了回调地狱问题。与 Express不同,Koa 不绑定任何中间件,而是提供了一套优雅的方法,帮助开发者快速而愉快地编写服务端应用程序。

2. 快速开始

2.1 初始化项目及安装

mkdir koa_testcd koa_testnpm i koa

2.2 创建 app.js

const Koa = require('koa');const app = new Koa();app.use(async ctx => {    ctx.body = 'Hello World';});app.listen(3000);

2.3 启动应用

node app.js

打开浏览器访问 http://localhost:3000/,即可看到 "Hello World"。

3. 路由

安装依赖

npm i koa-router

示例路由配置

const Koa = require('koa');const Router = require('koa-router');const app = new Koa();const router = new Router();router.get('/hello', (ctx) => {    ctx.body = 'Hello World';});app.use(router.routes()).use(router.allowedMethods());app.listen(3000);

4. 获取请求参数

路径参数

const Koa = require('koa');const Router = require('koa-router');const app = new Koa();const router = new Router();router.get('/hello/:name', (ctx) => {    ctx.body = 'Hello World,' + ctx.params.name;});app.use(router.routes()).use(router.allowedMethods());app.listen(3000);

访问 http://localhost:3000/hello/zhangshan,将显示 "Hello World,zhangshan"。

查询参数

router.get('/hello', (ctx) => {    ctx.body = 'Hello World,' + ctx.query.name;});

访问 http://localhost:3000/hello?name=zhangshan,将显示 "Hello World,zhangshan"。

请求体参数

需要安装 koa-body

npm i koa-body
const Koa = require('koa');const Router = require('koa-router');const bodyParser = require('koa-body');const app = new Koa();const router = new Router();app.use(bodyParser());router.post('/hello', (ctx) => {    ctx.body = 'Hello World,' + ctx.request.body.name;});app.use(router.routes()).use(router.allowedMethods());app.listen(3000);

使用 Postman 或 curl 发送 POST 请求:

curl -d '{"name":"zhangshan"}' -H "Content-Type: application/json" -X POST http://127.0.0.1:3000/hello

响应将显示 "Hello World,zhangshan"。

5. 响应数据

正常响应

router.post('/hello', (ctx) => {    const { name } = ctx.request.body;    const res = '[' + name + ']';    ctx.response.status = 200;    ctx.response.body = 'Hello World,' + res;});

发送 POST 请求,响应将显示 "Hello World,[zhangshan]"。

异常处理

router.post('/hello', (ctx) => {    const { name } = ctx.request.body;    if (!name) {        const err = new Error('name required');        err.status = 400;        err.expose = true;        throw err;    }    const res = '[' + name + ']';    ctx.response.status = 200;    ctx.response.body = 'Hello World,' + res;});

发送没有 name 属性的 POST 请求,响应将显示 "name required",状态码为 400。

6. 全局错误处理

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

7. 常用中间件

7.1 Koa-Logger

用于打印请求日志:

const KoaLogger = require('koa-logger');app.use(KoaLogger((str, args) => {    logger.debug(str);}));

7.2 Koa-Http-Request

用于发送 HTTP 请求:

const koaRequest = require('koa-http-request');app.use(koaRequest({    json: true,    timeout: 3000,    host: 'www.baidu.com'}));const result = await ctx.get('/');console.log(result);

7.3 Koa2-Swagger-UI

用于生成 Swagger UI:

const koaSwagger = require('koa2-swagger-ui');app.use(koaSwagger({    routePrefix: '/swagger',    swaggerOptions: {        url: '/api-docs.json',        hideTopbar: true    }}));

7.4 Koa-Convert 和 Koa2-Cors

用于设置跨域:

const convert = require('koa-convert');const cors = require('koa2-cors');app.use(convert(cors({    allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],    allowHeaders: ['Content-Type', 'Accept'],    origin: ctx => '*'})));

7.5 Koa-Compress

用于 gzip 压缩:

const compress = require('koa-compress');app.use(compress({    threshold: 2048,    flush: require('zlib').Z_SYNC_FLUSH}));

8. 常用 aliases

Request Aliases

  • ctx.header:获取请求头对象
  • ctx.headers:设置请求头对象
  • ctx.method:获取或设置请求方法
  • ctx.url:获取或设置请求 URL
  • ctx.originalUrl:获取原始 URL
  • ctx.origin:获取主机名和端口
  • ctx.href:获取完整 URL
  • ctx.path:获取或设置路径
  • ctx.query:获取或设置查询参数
  • ctx.querystring:获取或设置原始查询字符串
  • ctx.host:获取主机名
  • ctx.hostname:获取主机名
  • ctx.fresh:检查请求是否为"fresh"
  • ctx.stale:检查请求是否为"stale"
  • ctx.socket:获取 Socket 对象
  • ctx.protocol:获取协议(http 或 https)
  • ctx.secure:判断是否使用 HTTPS
  • ctx.ip:获取远程 IP
  • ctx.ips:获取 X-Forwarded-For IP
  • ctx.subdomains:获取子域名
  • ctx.is():判断内容类型
  • ctx.accepts():判断支持的内容类型

Response Aliases

  • ctx.body:获取或设置响应体
  • ctx.status:获取或设置状态码
  • ctx.message:获取或设置状态消息
  • ctx.length:获取或设置内容长度
  • ctx.type:获取或设置内容类型
  • ctx.headerSent:检查响应头是否已发送
  • ctx.redirect():进行重定向
  • ctx.attachment():提示下载
  • ctx.set():设置多个响应头字段
  • ctx.append():添加响应头字段
  • ctx.remove():移除响应头字段
  • ctx.lastModified:获取最后修改时间
  • ctx.lastModified:设置最后修改时间
  • ctx.etag:设置 ETag

9. 常用状态码

以下是 Koa 支持的所有状态码及其对应的文字描述:

100 continue101 switching protocols102 processing200 ok201 created202 accepted203 non-authoritative information204 no content205 reset content206 partial content207 multi-status208 already reported226 im used300 multiple choices301 moved permanently302 found303 see other304 not modified305 use proxy307 temporary redirect308 permanent redirect400 bad request401 unauthorized402 payment required403 forbidden404 not found405 method not allowed406 not acceptable407 proxy authentication required408 request timeout409 conflict410 gone411 length required412 precondition failed413 payload too large414 uri too long415 unsupported media type416 range not satisfiable417 expectation failed418 I'm a teapot422 unprocessable entity423 locked424 failed dependency426 upgrade required428 precondition required429 too many requests431 request header fields too large500 internal server error501 not implemented502 bad gateway503 service unavailable504 gateway timeout505 http version not supported506 variant also negotiates507 insufficient storage508 loop detected510 not extended511 network authentication required

转载地址:http://pfib.baihongyu.com/

你可能感兴趣的文章
OpenCV与AI深度学习 | 实战 | OpenCV传统方法实现密集圆形分割与计数(详细步骤 + 代码)
查看>>
OpenCV与AI深度学习 | 实战 | OpenCV实现扫描文本矫正应用与实现详解(附源码)
查看>>
OpenCV与AI深度学习 | 实战 | 使用YOLOv8 Pose实现瑜伽姿势识别
查看>>
OpenCV与AI深度学习 | 实战 | 使用YoloV8实例分割识别猪的姿态(含数据集)
查看>>
OpenCV与AI深度学习 | 实战 | 使用姿态估计算法构建简单的健身训练辅助应用程序
查看>>
OpenCV与AI深度学习 | 实战 | 基于YoloV5和Mask RCNN实现汽车表面划痕检测(步骤 + 代码)
查看>>
OpenCV与AI深度学习 | 实战 | 基于YOLOv9和OpenCV实现车辆跟踪计数(步骤 + 源码)
查看>>
OpenCV与AI深度学习 | 实践教程|旋转目标检测模型-TensorRT 部署(C++)
查看>>
OpenCV与AI深度学习 | 干货 | 深度学习模型训练和部署的基本步骤
查看>>
OpenCV与AI深度学习 | 手把手教你用Python和OpenCV搭建一个半自动标注工具(详细步骤 + 源码)
查看>>
OpenCV与AI深度学习 | 深度学习检测小目标常用方法
查看>>
Opencv中KNN背景分割器
查看>>
OpenCV中基于已知相机方向的透视变形
查看>>
OpenCV中的监督学习
查看>>
opencv中读写视频
查看>>
opencv之cv2.findContours和drawContours(python)
查看>>
opencv之namedWindow,imshow出现两个窗口
查看>>
opencv之模糊处理
查看>>
Opencv介绍及opencv3.0在 vs2010上的配置
查看>>
OpenCV使用霍夫变换检测图像中的形状
查看>>