简介

Koa 是一个新的 web 框架,由 Express 幕后的原班人马打造, 致力于成为 web 应用和 API 开发领域中的一个更小、更富有表现力、更健壮的基石。 通过利用 async 函数,Koa 帮你丢弃回调函数,并有力地增强错误处理。 Koa 并没有捆绑任何中间件, 而是提供了一套优雅的方法,帮助您快速而愉快地编写服务端应用程序。

安装

现在终端使用 npm init -y
在安装 koa npm i koa
如果要使用CommenJs,就直接使用
如果使用ES Module,则需要在package.json中设置一个属性 :”type”:”module”
image.png

简单使用

其中,ctx(context) 表示http请求的上下文。
ctx.body 通过这句代码向客户端响应内容。

  1. // 使用ES Module ,要在package.json中设置一个属性 :"type":"module"
  2. import koa from 'koa';
  3. // 创建实例对象
  4. const app = new koa();
  5. // 编写中间件
  6. // 中间件可以使用链式调用
  7. // 也可以使用多个app.use
  8. // app.use((ctx,next) =>{
  9. // // 处理信息
  10. // console.log('哈哈');
  11. // // 调用next()后才可以进行下一个中间件,处理下一个信息
  12. // next()
  13. // })
  14. // .use((ctx,next) =>{
  15. // console.log('你个大sb。');
  16. // next();
  17. // })
  18. // .use(ctx=>{
  19. // ctx.body = '啊( ̄︶ ̄)↗ ♥<( ̄︶ ̄)↗[GO!]';
  20. // })
  21. app.use((ctx,next) =>{
  22. // 处理信息
  23. console.log('哈哈');
  24. // 调用next()后才可以静茹下一个中间件,处理下一个信息
  25. next()
  26. });
  27. app.use((ctx,next) =>{
  28. console.log('你个大sb。');
  29. next();
  30. });
  31. // 最后需要使用ctx.body,向页面响应数据
  32. app.use(ctx=>{
  33. ctx.body = '啊( ̄︶ ̄)↗ ♥<( ̄︶ ̄)↗[GO!]';
  34. })
  35. // 监听
  36. app.listen(8080,()=>{
  37. console.log('server is running');
  38. })

image.png
image.png

获取请求信息

ctx.url

ctx.method

  1. import koa from 'koa';
  2. const app = new koa();
  3. app.use((ctx) => {
  4. //中国中间件获取请求信息
  5. console.log(ctx.url);
  6. //获取请求方法
  7. console.log(ctx.method);
  8. // ctx.url获取请求信息
  9. if (ctx.url.includes('/index.html')) {
  10. console.log('用户正在请求index页面');
  11. console.log(ctx.url.split('?')[1]);
  12. }
  13. // ... else if .......
  14. });
  15. app.listen(8080, () => {
  16. console.log('server is running...');
  17. });

洋葱圈问题

image.pngimage.png
在执行中间件时,会先执行next()之前的代码,在执行完最后一个中间件时,会反过来向上执行next()下面的代码,(比较类似于事件的捕获和冒泡过程)
每个中间件都接收了一个next参数,在next函数运行之前的中间件代码会在一开始就执行,next函数之后的代码会在内部的中间件全部运行结束之后才执行。

什么叫中间件

简单的说,所谓的中间件就是在请求和响应之间的处理程序,就可以称之为中间件。一般在请求和响应之间的业务较为复杂,那么将这些较为复杂的业务拆成一个个独立的函数来分别解决不同的问题,这就是中间件的主要作用。

  1. import koa from 'koa';
  2. const app = new koa();
  3. // 洋葱圈模型
  4. app.use((ctx, next) => {
  5. console.log('1-1');
  6. next();
  7. console.log('1-2');
  8. });
  9. app.use((ctx, next) => {
  10. console.log('2-1');
  11. next();
  12. console.log('2-2');
  13. });
  14. app.use((ctx, next) => {
  15. console.log('3-1');
  16. next();
  17. console.log('3-2');
  18. });
  19. app.use((ctx) => {
  20. ctx.body = 'hello,koa';
  21. });
  22. app.listen(8080, () => {
  23. console.log('server is running...');
  24. });

image.png

路由

建立URL和处理函数之间的对应关系

作用

根据不同的Method和URL返回不同的内容

安装

  1. npm i koa-router

使用步骤

  1. 1. 导入`koa-router`包
  2. 2. 实例化router对象
  3. 3. 使用router处理路由
  4. 4. 注册中间件

router

  1. import Router from "koa-router";
  2. // 实例化路由
  3. const router = new Router();
  4. //调用相应接口时要在文件前面加上前缀
  5. //(和java的controller一样)
  6. //router.prefix('/article'); // 接口前缀
  7. // 利用路由创建中间件
  8. // 所有的中间件都要使用koa的use方法使用,不能只创建中间件
  9. // get请求
  10. // 可以省略后缀
  11. router.get('/index',(ctx)=>{
  12. // console.log('这就是首页了[]~( ̄▽ ̄)~*');
  13. //通过ctx.body响应页面数据
  14. ctx.body = '你瞎啊啊φ(* ̄0 ̄)';
  15. })
  16. // post请求
  17. router.post('/as',(ctx)=>{
  18. // console.log('这他妈不是吗,你瞎啊啊φ(* ̄0 ̄)');
  19. // ctx.body = '你瞎啊啊φ(* ̄0 ̄)';
  20. // 如果要响应json格式的数据,则需要以下设置。
  21. ctx.set('Content-Type', 'application/json'); // 设置响应的数据是json
  22. ctx.body = JSON.stringify({ a: 100 });
  23. })
  24. // 导出router
  25. export default router;
  1. import koa from 'koa';
  2. import router from './appRouter.js';
  3. // 实例化对象
  4. const app = new koa();
  5. // 通过use注册router创建的中间件
  6. // 注册路由中间件
  7. app.use(router.routes());
  8. app.use(router.allowedMethods());
  9. // 监听服务
  10. app.listen(8080,()=>{
  11. console.log('server is running...( ̄︶ ̄)↗ ');
  12. })

image.png

  1. // 一. 导入koa
  2. const Koa = require('koa')
  3. // 二. 实例化对象
  4. const app = new Koa()
  5. // 三. 编写中间件
  6. app.use((ctx) => {
  7. if (ctx.url == '/') {
  8. ctx.body = '这是主页'
  9. } else if (ctx.url == '/users') {
  10. if (ctx.method == 'GET') {
  11. ctx.body = '这是用户列表页'
  12. } else if (ctx.method == 'POST') {
  13. ctx.body = '创建用户'
  14. } else {
  15. ctx.status = 405 // 不支持的请求方法
  16. }
  17. } else {
  18. ctx.status = 404
  19. }
  20. })
  21. // 四. 启动服务
  22. app.listen(3000, () => {
  23. console.log('server is running on http://localhost:3000')
  24. })

请求参数

koa-body

与koa-bodyparser类似

koa-bodyparser

用于解析post请求方式传递的参数

ctx.query

ctx.params

ctx.request.body

  1. import koa from 'koa';
  2. import router from './appRouter.js';
  3. import bodyParser from 'koa-bodyparser';
  4. // 实例化对象
  5. const app = new koa();
  6. // 处理post请求数据
  7. app.use(bodyParser());
  8. // 使用use注册中间件
  9. app.use(router.routes());
  10. app.use(router.allowedMethods());
  11. // 监听服务
  12. app.listen(8080,()=>{
  13. console.log('server is running...( ̄︶ ̄)↗ ');
  14. })
  1. import Router from "koa-router";
  2. // 实例化路由
  3. const router = new Router();
  4. // 利用路由创建中间件
  5. // 所有的中间件都要使用koa的use方法使用,不能只创建中间件
  6. // get请求
  7. // 可以省略后缀
  8. // router.get('/index',(ctx)=>{
  9. // // console.log('这就是首页了[]~( ̄▽ ̄)~*');
  10. // ctx.body = '你瞎啊啊φ(* ̄0 ̄)';
  11. // })
  12. // post请求
  13. router.post('/as',(ctx)=>{
  14. // console.log('这他妈不是吗,你瞎啊啊φ(* ̄0 ̄)');
  15. ctx.body = '你瞎啊啊φ(* ̄0 ̄)';
  16. })
  17. // 获取urlencoded类型的参数
  18. // 发送这样的请求:127.0.0.1:8080/index?user=a&name=hh
  19. router.get('/index',(ctx) =>{
  20. // 通过结构赋值的方式接受参数
  21. const {user,name} = ctx.query;
  22. console.log(ctx.query);
  23. console.log(user,name);
  24. ctx.body = 'ok';
  25. })
  26. // 获取动态参数: /index/:id/:usename
  27. // 发送这样的请求:127.0.0.1:8080/index/混合/123
  28. router.get('/index/:user/:pass',(ctx) => {
  29. const {user,pass} =ctx.params;
  30. console.log(ctx.params);
  31. console.log(user,pass);
  32. ctx.body = 'ok';
  33. })
  34. // 获取post请求传参
  35. router.post('/abc',(ctx) =>{
  36. // 返回的是一个对象
  37. const {a,b} = ctx.request.body;
  38. console.log(ctx.request.body)
  39. console.log(a,b);
  40. ctx.body= 'ok';
  41. })
  42. // 导出router
  43. export default router;

post传参
image.pngimage.png

跨域问题

放入白名单中

image.png

  1. import koa from 'koa';
  2. import router from './router/artical.js';
  3. import cors from '@koa/cors';
  4. const app = new koa();
  5. app.use(cors(
  6. {
  7. // 设置百名单,
  8. "origin":"http://127.0.0.1:5500",
  9. // 设置请求方式
  10. "allowMethods":"GET,POST"
  11. }
  12. ))
  13. app.use(router.routes());
  14. app.use(router.allowedMethods());
  15. app.listen(8080,()=>{
  16. console.log('server is running..');
  17. })
  1. import Router from 'koa-router';
  2. const router = new Router();
  3. // router.get('/artical',async (ctx) =>{
  4. // await ctx.render('artical');
  5. // })
  6. router.get('/artical',(ctx) => {
  7. ctx.set('content-type','application/json');
  8. const {id = 0} = ctx.query;
  9. if(id === 0) {
  10. ctx.body = JSON.stringify({
  11. errno: 100111,
  12. data: {},
  13. msg: 'id参数缺失,请检查参数',
  14. })
  15. }else if(id == 100) {
  16. ctx.body = JSON.stringify({
  17. errno: 100111,
  18. data: {
  19. title: '这是一篇测试文章',
  20. content: '这是用来测试接口的一篇文章.....',
  21. },
  22. msg: '',
  23. })
  24. }
  25. })
  26. export default router;
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>??</title>
  8. </head>
  9. <body>
  10. <h1>title</h1>
  11. <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quaerat voluptatum suscipit, nostrum temporibus accusantium officiis cumque velit commodi sequi enim impedit similique quisquam, neque doloremque tempora iusto necessitatibus! Neque, iure!</p>
  12. </body>
  13. <script>
  14. const xhr = new XMLHttpRequest();
  15. xhr.open('get','http://localhost:8080/artical?id=100');
  16. xhr.send();
  17. xhr.onreadystatechange = function() {
  18. if(xhr.status === 200) {
  19. if(xhr.readyState === 4){
  20. const data = JSON.parse(xhr.responseText);
  21. if (data.errno === 100111) {
  22. // 获取标题和内容
  23. const title = document.querySelector('h1');
  24. const p = document.querySelector('p');
  25. title.innerText = data.data.title;
  26. p.innerText = data.data.content;
  27. } else {
  28. console.error(data.msg);
  29. }
  30. }
  31. }else {
  32. console.error('失败');
  33. }
  34. }
  35. </script>
  36. </html>

方法二

image.png

generator

  1. npm i -g koa-generator

安装后在键入 koa ,再键入 npm install 安装依赖

多域携带cookies发送请求

如果你的前端地址只有一个,给@koa/cors的origin添加一个域名就能满足需求,如果需要支持跨域的域名有多个呢?
通过观察@koa/cors的 单元测试用例,可以发现origin是支持用函数的方式传入的。这样我们就可以维护一个域名数组,判断请求地址是否在域名数组内,就能知道是否要对请求地址提供携带cookies请求支持了。
要想知道发起请求的前端地址,可以使用ctx.request.header.origin。

  1. // 允许的域名数组
  2. arr_ym = ['http://www.baidu.com','https://www.sina.com.cn/','https://spec.csdn.net/']
  3. app.use(cors({
  4. origin(ctx) {
  5. if (arr_ym.includes(ctx.request.header.origin)) {
  6. // 响应代码
  7. }
  8. },
  9. credentials: true
  10. }));

注意ctx.request.header.origin和ctx.request.origin是不同的。ctx.request.origin是接口域名,ctx.request.header.origin是发起请求的页面域名。