2023-02-28
Nodejs
00

目录

1. Koa 的基本使用
1.1 认识 Koa
1.2 Koa 初体验
1.3 Koa 中间件
1.4 路由的使用
2. 参数解析
2.1 解析参数:params & query
2.2 解析参数:json
2.3 解析参数:x-www-form-urlencoded
2.4 解析参数 form-data
2.5 Multer 上传文件
2.6 静态服务器
2.7 数据的相应
2.8 错误处理

1. Koa 的基本使用

1.1 认识 Koa

在上一章我们已经介绍了 express,另外一个非常流行的 Node Web 服务器框架就是 Koa

Koa 官方的介绍:

  1. koa:next generation web framework for node.js
  2. koa:node.js 的下一代 web 框架

事实上,koaexpress 同一个团队开发的一个新的 Web 框架

  • 目前团队的核心开发者 TJ 的主要精力也在维护 Koaexpress 已经交给团队维护了;
  • Koa 旨在为 Web 应用程序和 API 提供更小、更丰富和更强大的能力;
  • 相对于 express 具有更强的异步处理能力(后续我们再对比);
  • Koa 的核心代码只有 1600+ 行,是一个更加轻量级的框架;
  • 我们可以根据需要安装和使用中间件;

下面我们就先来体验一下用 koa 的`Web服务器,创建一个接口。

1.2 Koa 初体验

既然我们要用 koa,那么第一步就需要先安装一下 koa

  1. 新建一个文件夹,在该文件夹下执行以下
SH
npm i koa
  1. 编写 js 文件
js
const Koa = require("koa"); const app = new Koa(); app.use((ctx, next) => { console.log("中间件 1"); next(); }); app.use((ctx, next) => { console.log("中间件 2"); ctx.response.body = "Hello World0"; }); app.listen(8000, () => { console.log("服务器在8000端口启动成功~"); });
  1. 通过 node 执行该文件,访问 localhost:8000

image.png

在上面的代码中,koa 注册的中间件提供了两个参数:

  1. ctx:上下文(Context)对象
    1. koa 并没有像 express 一样,将 reqres 分开,而是将它们作为 ctx 的属性;
    2. ctx 代表一次请求的上下文对象;
    3. ctx.request:获取请求对象;
    4. ctx.response:获取响应对象;
  2. next:本质上是一个 dispatch,类似于 express 中的 next

1.3 Koa 中间件

koa 通过创建的 app 对象,注册中间件只能通过 use 方法:

  1. koa并没有提供 methods 的方式来注册中间件;
  2. 也没有提供 path 中间件来匹配路径;

在真实开发中,我们可以通过以下方法将路径和 method 分离

  1. 根据 request 自己来判断
  2. 使用第三方路由中间件
js
app.use((ctx, next) => { if(ctx.request.path === '/users') { if(ctx.request.method === 'POST') { ctx.response.body = 'Create User Success~' } else { ctx.response.body = 'Users List~' } } else { ctx.response.body = 'Other Request Response' } })

1.4 路由的使用

koa 官方并没有给我们提供路由的库,我们可以选择第三方库:koa-router

  1. 安装 koa-router
sh
npm i @koa/router
  1. 我们可以先封装一个 users/router.js 文件
js
const KoaRouter = require("@koa/router"); const userRouter = new KoaRouter({ prefix: "/users" }); userRouter.get("/", (ctx, next) => { ctx.body = "用户列表~"; }); userRouter.post("/", (ctx, next) => { ctx.status = 201; ctx.body = "用户创建~"; }); module.exports = userRouter;
  1. index.js 中将 router.routes() 注册为中间件
js
const userRouter = require("./user/router.js"); const Koa = require("koa"); const app = new Koa(); app.use(userRouter.routes()); app.use(userRouter.allowedMethods()); app.listen(8000, () => { console.log("服务器在8000端口启动成功~"); });
  1. 运行 index.js 文件即可启动服务

注意:allowedMethods 用于判断某一个 method 是否支持:

  • 如果我们请求 get,那么是正常的请求,因为我们有实现 get;
  • 如果我们请求 put、delete、patch,那么就自动报错: Method Not Allowed,状态码:405
  • 如果我们请求 linkcopylock,那么久自动报错:Not Implemented,状态码:501

2. 参数解析

koa 的参数解析与 express 比较相似的只是有些细微的差别

2.1 解析参数:params & query

请求地址:http://localhost:8000/users/123

获取 params:

js
const userRouter = new Router({prefix: "/users"}) userRouter.get("/:id", (ctx, next) => { console.log(ctx.params.id) ctx.body = "Hello World" })

image.png

请求地址:http://localhost:8000/users/login?username=zhangsan&password=123

获取 query

js
userRouter.get("/login", (ctx, next) => { console.log(ctx.request.query); ctx.body = "Hello Wolrd"; });

image.png

2.2 解析参数:json

请求地址:http://localhost:8000/login

bodyjson 格式:

json
{ username: "zhangsan", password: "lisi" }

获取 json 数据:

  1. 安装依赖
sh
npm install koa-bodyparser
  1. 使用 koa-bodyparser 的中间件
js
const bodyParser = require('koa-bodyparser') app.use(bodyParser())
js
userRouter.post("/login", (ctx, next) => { console.log(ctx.request.body); ctx.status = 201; ctx.body = "用户创建~"; });

image.png

2.3 解析参数:x-www-form-urlencoded

请求地址:http://localhost:8000/login

bodyx-www-form-urlencoded 格式:

image.png

获取 json 数据:(和 json 是一致的)

js
const bodyParser = require('koa-bodyparser') app.use(bodyParser()) app.use((ctx,next) => { console.log(ctx.request.body) ctx.body = "Hello World" })

2.4 解析参数 form-data

请求地址:http://localhost:8000/login

bodyform-data 格式

image.png

解析 body 中的数据,我们需要使用 multer

  1. 安装依赖
sh
npm install koa-multer
  1. 使用 multer 中间件;
js
const multer = require("koa-multer"); const upload = multer({}); app.use(upload.any()); app.use((ctx, next) => { console.log(ctx.req.body); });

2.5 Multer 上传文件

js
const path = require("path"); const Router = require("@koa/router"); const multer = require("koa-multer"); const Koa = require("koa"); const app = new Koa(); const upload = multer({ storage: multer.diskStorage({ destination: (req, file, cb) => { cb(null, "./uploads/"); }, filename: (req, file, cb) => { cb(null, Date.now() + path.extname(file.originalname)); }, }), }); const fileRouter = new Router(); fileRouter.post("/upload", upload.single("avatar"), (ctx, nexy) => { console.log(ctx.req.file); ctx.body = "上传成功"; }); app.use(fileRouter.routes()); app.listen(8000, () => { console.log("服务器在8000端口启动成功~"); });

启动服务,在postman中上传一张图片

image.png

可以看到服务端已经存储了一张图片

image.png

2.6 静态服务器

koa 并没有内置部署相关的功能,所以我们需要使用第三方库

js
npm install koa-static

部署的过程类似于 express

js
const Koa = require('koa') const static = require('koa-static') const app = new Koa() app.use(static('./build')) app.use(8000, () => { console.log('静态服务器启动成功') })

2.7 数据的相应

输出结果:body将响应主体设置为以下之一:

  1. string :字符串数据
  2. Buffer :Buffer数据
  3. Stream :流数据
  4. Object|| Array:对象或者数组
  5. null :不输出任何内容
js
ctx.body = ['1','2','3'] // 或 ctx.response.body = {username: 'zhangsan', password: 'lisi'}

如果 response.status 尚未设置,Koa 会自动将状态设置为 200204

  1. 请求状态:status
ctx.status = 201 // 或者 ctx.response.status = 204

2.8 错误处理

const Koa = requrie('koa') const app = new Koa() app.use((ctx,next) => { ctx.app.emit('error', new Error('哈哈哈'), ctx) }) app.on('error', (err, ctx) => { console.log(err.message) ctx.response.body = '哈哈哈' }) app.listen(8000, () => { console.log('错误处理服务器启动成功~') })
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:叶继伟

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!