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()

想执行下一个中间件,必须调用next()

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

1-5使用cheerio解析html

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