0


大数据BI可视化(Echarts组件)项目开发-熟悉koa2后端开发6.0

koa2简介

1.基于Node.js平台的web开发框架

2.由Express原班人马打造 Express,koa,koa2
框架名作用异步处理Expressweb框架回调函数koaweb框架Generator+yieldkoa2web框架async/await
3.环境依赖Node.js V7.6.0以上

koa2特点

1.支持async/await

2.洋葱模型的中间件

  1. 对于web服务器可以理解接收每一个请求再处理每一个响应返回游览器,而请求到达服务器需要程序处理称洋葱模型的中间件;
  2. 层级中间件优先级最外围第一层中间件,先进先出原理(共三层:请求服务器->1->2->3->2->1->回响浏览器)

koa2快速上手

1.检查Node环境

node -v

2.安装koa

npm init -y

npm install koa

3.创建并编写app.js文件

  • 创建koa对象
  • 编写响应函数(中间件)
  • 监听端口

4.启动服务器

koa2项目

1.创建

npm init -y

npm install koa

2.创建app.js

  1. // 1.创建koa对象
  2. const Koa = require('koa')
  3. const app = new Koa()
  4. // 2.编写响应函数(中间件)
  5. // ctx:上下文,web容器,ctx.request ctx.response
  6. // next: 下一个中间件,下一层中间件是否能够得到执行, 取决于next这个函数有没有被调用
  7. app.use((ctx, next) => {
  8. console.log(ctx.request.url)
  9. ctx.response.body = 'hello world'
  10. })
  11. // 3.绑定端口号 3000
  12. app.listen(3000)

3.启动

node app.js

中间件特点

  • koa对象通过use方法加入中间件
  • 一个中间件就是一个函数
  • 中间件顺序符合洋葱模型
  • 内层中间件能否执行取决于外层中间件的next函数调用
  • 调用next函数得到的是Promise对象

1.1验证请求顺序

  1. // 1.创建koa对象
  2. const Koa = require('koa')
  3. const app = new Koa()
  4. // 2.编写响应函数(中间件)
  5. // ctx:上下文,web容器,ctx.request ctx.response
  6. // next: 下一个中间件,下一层中间件是否能够得到执行, 取决于next这个函数有没有被调用
  7. app.use((ctx, next) => {
  8. console.log('第一层中间件')
  9. ctx.response.body = 'hello world'
  10. next()
  11. })
  12. // 第二层中间件
  13. app.use((ctx, next) => {
  14. console.log('第二层中间件')
  15. next()
  16. })
  17. // 第三层中间件
  18. app.use((ctx, next) => {
  19. console.log('第三层中间件')
  20. next()
  21. })
  22. // 3.绑定端口号 3000
  23. app.listen(3000)

1.2验证响应顺序

  1. // 1.创建koa对象
  2. const Koa = require('koa')
  3. const app = new Koa()
  4. // 2.编写响应函数(中间件)
  5. // ctx:上下文,web容器,ctx.request ctx.response
  6. // next: 下一个中间件,下一层中间件是否能够得到执行, 取决于next这个函数有没有被调用
  7. app.use((ctx, next) => {
  8. console.log('第一层中间件...1')
  9. ctx.response.body = 'hello world'
  10. next()
  11. console.log('第一层中间件...2')
  12. })
  13. // 第二层中间件
  14. app.use((ctx, next) => {
  15. console.log('第二层中间件...1')
  16. next()
  17. console.log('第二层中间件...2')
  18. })
  19. // 第三层中间件
  20. app.use((ctx, next) => {
  21. console.log('第三层中间件')
  22. next()
  23. })
  24. // 3.绑定端口号 3000
  25. app.listen(3000)

1.3调用next函数得到的是Promise对象

  1. // 1.创建koa对象
  2. const Koa = require('koa')
  3. const app = new Koa()
  4. // 2.编写响应函数(中间件)
  5. // ctx:上下文,web容器,ctx.request ctx.response
  6. // next: 下一个中间件,下一层中间件是否能够得到执行, 取决于next这个函数有没有被调用
  7. app.use((ctx, next) => {
  8. console.log('第一层中间件...1')
  9. ctx.response.body = 'hello world'
  10. next()
  11. console.log('第一层中间件...2')
  12. })
  13. // 第二层中间件
  14. app.use(async (ctx, next) => {
  15. console.log('第二层中间件...1')
  16. const ret = await next()
  17. console.log(ret)
  18. console.log('第二层中间件...2')
  19. })
  20. // 第三层中间件
  21. app.use((ctx, next) => {
  22. console.log('第三层中间件')
  23. next()
  24. return 'i love the dog'
  25. })
  26. // 3.绑定端口号 3000
  27. app.listen(3000)

后台项目

  • 计算服务器处理请求的总耗时
  • 在响应头上加上响应内容的mime类型
  • 根据url读取指定目录下文件内容
    项目准备总耗时中间件响应头中间件业务逻辑中间件允许跨域

    项目准备

1.安装包

npm init -y

npm install koa

2.创建文件和目录结构

app.js

data/存放数据

middleware/中间层

  1. koa_response_data.js 业务逻辑
  2. koa_response_duration.js 请求耗时
  3. koa_response_header.js 响应

utils/

  1. file_utils.js 帮助快速读取某个目录下文件

3.app.js

  1. // 服务器的入口文件
  2. // 1.创建KOA的实例对象
  3. const Koa = require('koa')
  4. const app = new Koa()
  5. // 2.绑定中间件
  6. // 绑定第一层中间件
  7. const respDurationMiddleware = require('./middleware/koa_response_duration')
  8. app.use(respDurationMiddleware)
  9. // 绑定第二层中间件
  10. const respHeaderMiddleware = require('./middleware/koa_response_header')
  11. app.use(respHeaderMiddleware)
  12. // 绑定第三层中间件
  13. const respDataMiddleware = require('./middleware/koa_response_data')
  14. app.use(respDataMiddleware)
  15. // 3.绑定端口号 8888
  16. app.listen(8888)

4.总耗时中间件

  1. // 计算服务器消耗时长的中间件
  2. module.exports = async (ctx, next) => {
  3. // 记录开始时间
  4. const start = Date.now()
  5. // 让内层中间件得到执行
  6. await next()
  7. // 记录结束的时间
  8. const end = Date.now()
  9. // 设置响应头 X-Response-Time
  10. const duration = end - start
  11. // ctx.set 设置响应头
  12. ctx.set('X-Response-Time', duration + 'ms')
  13. }

5.响应头中间件

  1. // 设置响应头的中间件
  2. module.exports = async (ctx, next) => {
  3. const contentType = 'application/json; charset=utf-8'
  4. ctx.set('Content-Type', contentType)
  5. ctx.set("Access-Control-Allow-Origin", "*")
  6. ctx.set("Access-Control-Allow-Methods", "OPTIONS, GET, PUT, POST, DELETE")
  7. await next()
  8. }

6.业务逻辑中间件

  1. // 处理业务逻辑的中间件,读取某个json文件的数据
  2. const path = require('path')
  3. const fileUtils = require('../utils/file_utils')
  4. module.exports = async (ctx, next) => {
  5. // 根据url
  6. const url = ctx.request.url // /api/seller ../data/seller.json
  7. let filePath = url.replace('/api', '') // /seller
  8. filePath = '../data' + filePath + '.json' // ../data/seller.json
  9. filePath = path.join(__dirname, filePath)
  10. try {
  11. const ret = await fileUtils.getFileJsonData(filePath)
  12. ctx.response.body = ret
  13. } catch (error) {
  14. const errorMsg = {
  15. message: '读取文件内容失败, 文件资源不存在',
  16. status: 404
  17. }
  18. ctx.response.body = JSON.stringify(errorMsg)
  19. }
  20. console.log(filePath)
  21. await next()
  22. }

7.工具类获取数据

  1. // 读取文件的工具方法
  2. const fs = require('fs')
  3. module.exports.getFileJsonData = (filePath) => {
  4. // 根据文件的路径, 读取文件的内容
  5. return new Promise((resolve, reject) => {
  6. fs.readFile(filePath, 'utf-8', (error, data) => {
  7. if(error) {
  8. // 读取文件失败
  9. reject(error)
  10. } else {
  11. // 读取文件成功
  12. resolve(data)
  13. }
  14. })
  15. })
  16. }

允许跨域

  • 实际是通过Ajax访问服务器

  • 同源策略

    1. 同协议/同域名/同端口
    2. 当前页面地址和Ajax获取数据的地址
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>Document</title>
  8. <script src="lib/jquery-1.12.2.js"></script>
  9. </head>
  10. <body>
  11. <button>点我试试</button>
  12. <script>
  13. $('button').click(function(){
  14. // http://127.0.0.1:5500/index.html
  15. // 发起ajax的请求 http://127.0.0.1:8888/api/map
  16. $.ajax({
  17. type: 'get',
  18. url: 'http://127.0.0.1:8888/api/map',
  19. success: function(data){
  20. console.log(data)
  21. }
  22. })
  23. })
  24. </script>
  25. </body>
  26. </html>

本文转载自: https://blog.csdn.net/2201_75311251/article/details/138304036
版权归原作者 阿龙要当程序猿 所有, 如有侵权,请联系我们删除。

“大数据BI可视化(Echarts组件)项目开发-熟悉koa2后端开发6.0”的评论:

还没有评论