博客
关于我
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商品评论数据采集与分析可视化系统 Flask框架 requests爬虫 NLP情感分析 毕业设计 源码
查看>>
python商品数据分析可视化系统(带爬虫)京东销售数据分析 计算机毕业设计 源码下载
查看>>
python商品库存管理系统 django框架 商品网站 MySQL数据库 源码下载 计算机毕业设计
查看>>
Python哪个版本最稳定好用2023.10.19
查看>>
Python和黑客技术的渊源
查看>>
Python和RF编写接口自动化
查看>>
Python和RF编写web自动化
查看>>
python和js哪个难_【Python】记一次学习,Python 与 js 在实现闭包时的差异
查看>>
python和java哪个更值得学——来自知乎高赞回答
查看>>
python和c混合编程 github_在pycharm中使用git版本管理以及同步github的方法
查看>>
python命名空间更改_Python模块xml.etree.ElementTree自动修改xml命名空间键
查看>>
Python命名中尾随下划线有什么好处?
查看>>
Python启动脚本
查看>>
Python听写汇总结果
查看>>
python吊打Excel?屁!那是你不会用!
查看>>
Python合并两张图片 | 先叠透明度再合并 (附Demo)
查看>>
python各进制的表述与转换
查看>>
python各种库安装
查看>>
python可视化matplotlib_如何使用Python中最强大的可视化工具Matplotlib?
查看>>
python可维护性_使用这7大神器,让你的Python 代码更容易于维护
查看>>