Koa 框架简介

一句话简介

基于 Node.js 的下一代 Web框架

基于 nodejs: 代表了它是 nodejs 的模块
下一代: 第一代 web 框架是 Express
web 框架: 不是命令行工具, 不是算法. koa 就是 web 开发框架, 写 api 写 web 应用的

操作步骤:

  • 初始化项目
npm init  初始化一个文件夹
  • 安装 Koa
npm i koa --save
  • 编写 Hello world
新建一个 js 文件:

const Koa = require('koa');
//实例化一个实例赋到 app 上, 这就是我们搭建的应用程序都在这个 app 里
const app = new Koa();  

// 如何 接收请求 返回 hello world, 使用 use 方法
// use 方法里可以传递一个函数, 这个函数就是中间件, 中间件里面可以返回返回值
// ctx 是上下文的缩写
app.use((ctx) => {
    
    
  ctx.body = 'hello world'
});

// 指定监听端口
app.listen(3000);
  • 自动重启小技巧
安装 nodemon
npm i nodemon --save-dev

因为不是全局安装 nodemon, 所以要在 package.json 里配置脚本命令
  "scripts": {
    
    
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  改成
    "scripts": {
    
    
    "start": "nodemon index.js"
  },

然后终端 npm start 就可以自动执行了

路由的作用

处理不同的 URL
处理不同的 http 方法
解析 url 上的参数


编写简单的 koa 中间件

处理不同的 URL:

app.use(async (ctx) => {
    
    
  // 先判断请求的是什么
  if(ctx.url === '/') {
    
    
    ctx.body = '这是主页';
  } else if (ctx.url === '/users') {
    
    
    ctx.body = '这时用户列表页'
  } else {
    
    
    ctx.status = 404;
  }
});

处理不同的 HTTP 方法

app.use(async (ctx) => {
    
    
  // 先判断请求的是什么
  if(ctx.url === '/') {
    
    
    ctx.body = '这是主页';
  } else if (ctx.url === '/users') {
    
    
    if(ctx.method === 'GET') {
    
    
      ctx.body = '这是用户列表页';
    } else if (ctx.method === 'POST') {
    
    
      ctx.body = '创建用户'
    } else {
    
    
      ctx.status = 405;
    }
  } else {
    
    
    ctx.status = 404;
  }
});

koa-router 实现路由

猜你喜欢

转载自blog.csdn.net/m0_48446542/article/details/109085225
koa