node koa常用属性、方法和常用中间件

╰半夏微凉° 2023-07-07 05:39 50阅读 0赞

request

常用API:

例子:http://localhost:4000/index?name=lxc&age=20

ctx.request.query -> 获取简析的查询字符串,无则返回空对象 { name: ‘lxc’, age: ‘20’ }

ctx.request.querystring -> 获取原始查询字符串 *name=lxc&age=20*

ctx.request.url -> 获取请求的url /index?name=lxc&age=20

ctx.request.path -> 获取path路径名 /index

ctx.request.method -> 获取请求方法 GET

ctx.request.host -> 获取主机 localhost:4000

ctx.request.hostname -> 获取主机名 localhost

例子:http://localhost:4000/index/:id

ctx.request.params-> 获取动态请求参数 { id: xxx }

ctx.request.header -> 设置请求头 (等于ctx.request.headers)

ctx.request.originalUrl -> 获取原始的URL(与ctx.request.url 相同)

ctx.request.href-> 获取完整的请求url http://localhost:4000/index?name=lxc&age=20

ctx.request.search -> 获取原始的查询字符串 ?name=lxc&age=20

ctx.request.type -> 获取请求的 content-type,不含 ‘charset’等参数 application/json

ctx.request.protocol -> 获取请求协议 http 或 https

post请求 {username: ‘lxc’, password: ‘123456’}

ctx.request.body-> 获取请求body ( 前提需要安装koa-bodyparser ) {username: ‘lxc’, password: ‘123456’}

#

response

ctx.response.status -> 设置响应状态(默认为404 - Not Found ,原生node的res.statusCode为200)

ctx.response.header -> 设置响应头对象 (等于ctx.response.headers)

ctx.response.body -> ,设置响应体内容 === ctx.body 可设置以下类型:

· string (Content-Type 默认为 text/htmltext/plain, 同时默认字符集是 utf-8)

· Buffer (Content-Type 默认为 application/octet-stream)

· Stream管道 * (Content-Type 默认为 application/octet-stream)*

· Object || Array (需要JSON.stringify( ) ,Content-Type 默认为 application/json

· null 无响应内容

tips: 如果未设置ctx.response.status,koa自动设置状态为200或204

ctx.response.redirect( url, [alt] )-> 设置重定向 参数二可选

ctx.response.set( ‘key’, ‘value’ )-> 设置响应头, 参数也可以是一个对象,设置多个响应头

ctx.response.append( ‘link’, ‘http://127.0.0.1‘ )-> 附加额外的消息头

ctx.response.type = xxx -> 设置响应的content-type

  1. ctx.type = 'text/plain; charset=utf-8';

实例属性:

app.context -> 它就是创建ctx的原型,可以通过编辑app.context 为ctx添加属性或方法(就是在ctx的原型上添加属性)

上下文:

koa中的上下文封装了Request对象和Response对象,详情见koa源码或者我写的一个简易的koa:

https://github.com/lvxingchenGit/LKoa

ctx.state -> 命名空间,传递信息的。

  1. // eg:
  2. ctx.state.user = await User.find(id)

ctx.app -> 实例的引用(就是实例)

多个中间件组合成单一中间件:

koa-compose - 包

  1. // npm i koa-compose --save
  2. const compose = require('koa-compose')
  3. async function m1(ctx, next){
  4. console.log('1')
  5. await next()
  6. }
  7. async function m2(ctx, next){
  8. console.log('2')
  9. await next()
  10. }
  11. async function m3(ctx, next){
  12. console.log('3')
  13. await next()
  14. }
  15. const all = componse([m1, m2, m3])
  16. app.use(all) // 总之中间件最后需要挂载到app.use()中

小案例:

前端请求 - 计算服务器响应时间

  1. app.use(async (ctx, next) => {
  2. const prevTime = new Date().getTime()
  3. await next()
  4. const nowTime = new Date().getTime()
  5. console.log('time:', nowTime - prevTime + 'ms') // 4ms
  6. ctx.body = {
  7. name: 'lxc'
  8. }
  9. })
  10. app.use(async (ctx, next) => {
  11. console.log('1')
  12. })

补充:

koa中使用原生的node request对象、response对象,还有几个常用属性:

  • ctx.request: koa 封装的 request 对象,中间件应该尽量使用
  • ctx.req:Node.js 原生的 request 对象
  • ctx.response:koa 封装的 response 对象,中间件应该尽量使用
  • ctx.res:Node.js 原生的 response 对象
  • ctx.state:koa 推荐的命名空间,用于通过中间件传递信息到前端视图
  • ctx.app:对应用实例 app 的引用

常用的koa中间件

koa-bodyparser

这个中间件可以将post请求的参数转为json格式返回。

koa接收到的post请求参数并不是json格式,我们需要将其转换为json
使用方法:安装后直接在ctx.request.body内获取POST请求参数,中间件自动给我们解析为json

  1. // 解析post请求中的参数
  2. const bdparser = require('koa-bodyparser')
  3. app.use(bdparser()) // 加载koa-bodyparser中间件

koa-router

  1. // koaRouter.js 路由请求
  2. const Router= require('koa-router')
  3. const user = new Router({prefix: '/v1'}) // prefix 可在prefix定义公共前缀路径
  4. user.get('/user', ctx => {
  5. ctx.body = {
  6. err_code = 'OK'
  7. }
  8. })
  9. user.post('/addOne', ctx => {})
  10. module.exports = {
  11. user
  12. }
  13. // --------------------------------------------
  14. // app.js
  15. const koa = require('koa')
  16. const { user } = require('./koaRouter')
  17. const app = koa()
  18. app.use(user.routes()) // 加载user中间件

20200221102940876.png

#

nodemon

  1. // 自动加载服务: Terminal 运行:
  2. nodemon projectName.js

require-directory

  1. // 自动查找文件夹 - 加载文件路径
  2. // 在项目开发过程中,往往各个路由模块会有多个文件,使用require 导入路由很麻烦,require-derectory可自动查找一个文件夹下的所有模块
  3. const requireDirectory = require('require-directory')
  4. const ABSOLUTE_URL = `${proccess.cwd()}/user`
  5. requireDirectory(module, ABSOLUTE_URL, {
  6. visit(){}
  7. })
  8. /**
  9. 参数一:module 不需要修改
  10. 参数二:要查找的文件夹,绝对路径,proccess.cwd()输出当前项目的绝对路径;
  11. __dirname:输出当前文件所在文件夹的绝对路径。
  12. 参数三:对象options配置项,如下:
  13. */
  14. /**
  15. {
  16. include: /name+\.js/g, // 白名单,只加载符合条件的,可使用正则或函数(参数为path - 模块的绝对路径)
  17. // include 值也可以是一个函数,返回true表示符合加载条件:
  18. include(path) {
  19. if(/.+\.js$/g.test(path)) {
  20. return true
  21. }
  22. },
  23. exclude(path){ // 黑名单,不加载的模块
  24. return /name+\.js/g.test(path) // 返回Boolean
  25. },
  26. visit(obj) { // 每个模块加载时执行的加载函数,参数为 module.exports 导出的模块
  27. app.use(obj) // 在这里边通常会把所有路由中间件挂载到app.use()中
  28. },
  29. rename: function(name) { // 重命名键名
  30. console.log(name) 会把所有的文件夹名及文件名打印出来!!!
  31. return name.toUpperCase()
  32. },
  33. recurse: true // 是否遍历文件夹,默认为true,嵌套文件夹下的模块也会被加载
  34. }
  35. */

封装自动导出路由文件

  1. const Router = require('koa-router')
  2. const requireDirectory = require('require-directory')
  3. const baseULR = process.cwd()
  4. class InitRouter {
  5. static InitRouterFn(app) {
  6. InitRouter.app = app
  7. InitRouter.runRouterMounting()
  8. }
  9. static runRouterMounting() {
  10. let whiteRulesReg = /.+\.js/g // 正则制定规则 - 哪些js文件可以导出
  11. requireDirectory(module, `${baseULR}/api`, {
  12. include(path) {
  13. if(whiteRulesReg.test(path)) {
  14. console.log('path', path) // 这里可以打印出符合匹配规则的文件路径
  15. return true // 返回true为白名单;返回false为黑名单
  16. }
  17. },
  18. visit(exportRouters) { // 兼容 module.exports = xxx 和 module.exports = {}
  19. if(exportRouters instanceof Router) {
  20. InitRouter.app.use(exportRouters.routes())
  21. }else {
  22. Object.keys(exportRouters).forEach(ele => {
  23. if(exportRouters[ele] instanceof Router) {
  24. InitRouter.app.use(exportRouters[ele].routes())
  25. }
  26. })
  27. }
  28. }
  29. })
  30. }
  31. }
  32. // 导出类
  33. module.exports = {
  34. InitRouter
  35. }

发表评论

表情:
评论列表 (有 0 条评论,50人围观)

还没有评论,来说两句吧...

相关阅读

    相关 RPC消息中间

    *一、消息中间件** 消息队列技术是分布式应用间交换信息的一种技术。消息队列可驻留在内存或磁盘上,队列存储消息直到它们被应用程序读走。通过消息队列,应用程序可独立地执行...

    相关 消息中间比较

    语 : 消息队列是分布式系统中重要的组件,在很多生产环境如商品抢购等需要控制并发量的场景下都需要用到。最近组内需要做流水server的选型升级,这里对消息队列及常见的消息...

    相关 node - koa中间

    koa中的中间件分析: 输出的顺序模拟了koa的洋葱模型,借着输出结果,分析下输出下边结果的原因: 使用async和await,说明中间件参数函数是异步函数,因为里边的