博客
关于我
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/

你可能感兴趣的文章
python | yagmail,一个实用的 Python 库!
查看>>
python | 一文掌握Python的上下文管理器和with语句
查看>>
python | 一文看懂Python闭包机制与变量作用域规则
查看>>
python读取含中文的json
查看>>
python | 如何用Python锁避免并发错误?
查看>>
python | 提升代码迭代速度的Python重载方法
查看>>
python | 深入理解Python并发编程中的GIL限制与解决方案
查看>>
Python | 爬虫实战——亚马逊搜索页监控(附详细源码)
查看>>
python | 高效使用Python工具自动生成模块文档的秘诀
查看>>
python 一个list去除另一个list中的值
查看>>
python 三大框架的 介绍。
查看>>
Python 下载的 11 种姿势,一种比一种高级!
查看>>
python读取一个文件夹下所有图片_初学Python-找出文件夹下的所有图片
查看>>
Python 中 3 个不可思议的返回功能
查看>>
python 中 dict 的另一种用法
查看>>
Python 中 PIL 读取图片出现异常旋转的解决方法
查看>>
python读取word表格内容(1)
查看>>
python 中os.path.join 双斜杠的解决办法
查看>>
python 中PIL.Image和OpenCV图像格式相互转换
查看>>
Python 中Semaphore 信号量对象、Event事件、Condition
查看>>