0
点赞
收藏
分享

微信扫一扫

Koa2的使用

_鱼与渔_ 2022-01-12 阅读 61

基于Node.js平台的web开发框架---- async / await

1.检查Node环境、安装Koa

node  -v
npm  init -y
npm install koa

2.创建文件和文件夹

① app.js文件:-- 入口文件

// 引入koa
const Koa = require('koa')
// 创建koa实例对象
const app = new Koa()
// 编写响应函数    洋葱模型的中间件

// 第一层中间件--总耗时中间件
const respDurationMiddleware = require('./middleware/koa_response_duration')
app.use(respDurationMiddleware)

// 第二层中间件--响应头中间件
const respHeaderMiddleware = require('./middleware/koa_response_header')
app.use(respHeaderMiddleware)

// 第三层中间件--业务逻辑中间件
const resDataMiddleware = require('./middleware/koa_response_data')
app.use(resDataMiddleware)

// 监听端口
app.listen(8888) //127.0.0.1:8888
// 启动服务器 命令行敲命令 node app.js

② data文件夹: -- 存放json数据

③ middleware文件夹:-- 中间件

koa_response_duration.js文件:

module.exports = async (ctx, next) => {
  //记录开始的时间
  const start = Date.now()
  await next()
  //记录结束的时间
  const end = Date.now()
  // 计算服务器总耗时时长
  const duration = end - start
  ctx.set('X-Response-Time', duration + 'ms')
}

koa_response_header.js文件:

module.exports = async (ctx, next) => {
  const contentType = 'application/json;charset=utf-8'
  // 响应头
  ctx.set('Content-Type', contentType)
  // ctx.response.body = '{"success" : true}';

  // 设置响应头  允许跨域
  ctx.set('Access-Control-Allow-Origin', '*')
  ctx.set('Access-Control-Allow-Methods', 'OPTIONS,GET,PUT,DELETE')

  await next()
}

koa_response_data.js文件:

// 业务逻辑中间件
const path = require('path')
const fileUtils = require('../utils/file_utils')
module.exports = async (ctx, next) => {
  //浏览器请求路径url -- /api/seller
  const url = ctx.request.url //
  //   将/api / seller   换成 ../data/seller.json
  let filePath = url.replace('/api', '')
  filePath = '../data' + filePath + '.json'
  filePath = path.join(__dirname, filePath)

  try {
    const ret = await fileUtils.getFileJsonData(filePath)
    ctx.response.body = ret
  } catch (error) {
    const errorMsg = {
      message: '读取文件内容失败,文件资源不存在',
      status: 404
    }
    ctx.response.body = JSON.stringify(errorMsg)
  }
  console.log(filePath)
  await next()
}

④ utils文件夹中:-- 工具文件

file_utils.js文件:

// 读取文件的工具方法
const fs = require('fs')
module.exports.getFileJsonData = filePath => {
  //   return "你好";
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (error, data) => {
      if (error) {
        reject(error)
      } else {
        resolve(data)
      }
    })
  })
}
举报

相关推荐

0 条评论