中间件

匹配路由之前和路由完成之后进行的操作就叫中间件

1-1 中间件函数

  1. const koa = require("koa");
  2. const app = new koa();
  3. /*
  4. app.use()中间件 -->就是一些第三方的模块
  5. 特点:
  6. 1.一个应用程序是可以有多个中间件
  7. */
  8. /* next就是下一个中间函数 */
  9. app.use(async (ctx,next)=>{
  10. console.log(1)
  11. console.log(next())
  12. })
  13. app.use(async ctx=>{
  14. console.log(2)
  15. return 3;
  16. })
  17. app.listen(8080)

**

1-2 中间件next()

  1. 想执行下一个中间件,必须调用next()
  2. const koa = require("koa");
  3. const app = new koa();
  4. /*
  5. app.use()中间件 -->就是一些第三方的模块
  6. 特点:
  7. 1.一个应用程序是可以有多个中间件
  8. */
  9. /*
  10. 1.next就是下一个中间函数
  11. 2.调用next()的时候下个中间会执行
  12. 3.阻塞了当前函数
  13. */
  14. app.use(async (ctx,next)=>{
  15. console.log(1)
  16. var res = await next();
  17. console.log(res);
  18. })
  19. app.use(async ctx=>{
  20. console.log(2)
  21. return 3;
  22. })
  23. app.listen(8080)

1-3 洋葱模型

  1. const koa = require("koa");
  2. const app = new koa();
  3. /* koa洋葱模型 */
  4. app.use(async (ctx,next)=>{
  5. console.log(1)
  6. await next();
  7. console.log(4)
  8. })
  9. app.use(async (ctx,next)=>{
  10. console.log(2)
  11. await next();
  12. console.log(3)
  13. })
  14. app.listen(8080)

中间件 - 图1

1-4 安装路由中间件

  1. # 1.安装依赖
  2. cnpm i koa-router -S
  3. # 2.导入模块并配置
  4. const koa = require("koa");
  5. const app = new koa();
  6. const Router = require("koa-router");
  7. const router = new Router();
  8. router.get("/",async ctx=>{
  9. ctx.body = "hello world"
  10. })
  11. app.use(router.routes());
  12. app.listen(8080)


1-5 使用cheerio解析html

  1. cnpm i cheerio -S
  2. const koa = require("koa");
  3. const app = new koa();
  4. const Router = require("koa-router");
  5. const router = new Router();
  6. const axios = require("axios");
  7. const cheerio = require("cheerio");
  8. const url = "https://movie.douban.com/top250"
  9. router.get("/douban",async ctx=>{
  10. var html = await axios.get(url);
  11. const $ = cheerio.load(html.data,{
  12. decodeEntities:false //解码设置为false,中文不会乱码
  13. });
  14. var title = $("#content h1").html();
  15. console.log(title)
  16. ctx.body = title;
  17. })
  18. app.use(router.routes());
  19. app.listen(8080)
  20. /*
  21. 1.axios抓取豆瓣
  22. 2.cheerio解析页面
  23. 3.返回数据给前端
  24. */