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

你可能感兴趣的文章
notepad++最详情汇总
查看>>
notepad++正则表达式替换字符串详解
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
nova基于ubs机制扩展scheduler-filter
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>