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

你可能感兴趣的文章
Nginx配置ssl实现https
查看>>
Nginx配置TCP代理指南
查看>>
Nginx配置——不记录指定文件类型日志
查看>>
Nginx配置代理解决本地html进行ajax请求接口跨域问题
查看>>
Nginx配置参数中文说明
查看>>
Nginx配置好ssl,但$_SERVER[‘HTTPS‘]取不到值
查看>>
Nginx配置如何一键生成
查看>>
Nginx配置实例-负载均衡实例:平均访问多台服务器
查看>>
NHibernate学习[1]
查看>>
NIFI1.21.0_Mysql到Mysql增量CDC同步中_日期类型_以及null数据同步处理补充---大数据之Nifi工作笔记0057
查看>>
NIFI1.21.0_NIFI和hadoop蹦了_200G集群磁盘又满了_Jps看不到进程了_Unable to write in /tmp. Aborting----大数据之Nifi工作笔记0052
查看>>
NIFI1.21.0通过Postgresql11的CDC逻辑复制槽实现_指定表多表增量同步_增删改数据分发及删除数据实时同步_通过分页解决变更记录过大问题_02----大数据之Nifi工作笔记0054
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_配置binlog_使用处理器抓取binlog数据_实际操作01---大数据之Nifi工作笔记0040
查看>>
NIFI从MySql中增量同步数据_通过Mysql的binlog功能_实时同步mysql数据_配置数据路由_实现数据插入数据到目标数据库_实际操作03---大数据之Nifi工作笔记0042
查看>>
NIFI同步MySql数据_到SqlServer_错误_驱动程序无法通过使用安全套接字层(SSL)加密与SQL Server_Navicat连接SqlServer---大数据之Nifi工作笔记0047
查看>>
Nifi同步过程中报错create_time字段找不到_实际目标表和源表中没有这个字段---大数据之Nifi工作笔记0066
查看>>
NIFI大数据进阶_离线同步MySql数据到HDFS_02_实际操作_splitjson处理器_puthdfs处理器_querydatabasetable处理器---大数据之Nifi工作笔记0030
查看>>
NIFI大数据进阶_连接与关系_设置数据流负载均衡_设置背压_设置展现弯曲_介绍以及实际操作---大数据之Nifi工作笔记0027
查看>>
NIFI数据库同步_多表_特定表同时同步_实际操作_MySqlToMysql_可推广到其他数据库_Postgresql_Hbase_SqlServer等----大数据之Nifi工作笔记0053
查看>>
NIFI汉化_替换logo_二次开发_Idea编译NIFI最新源码_详细过程记录_全解析_Maven编译NIFI避坑指南001---大数据之Nifi工作笔记0068
查看>>