Koa的学习

Koa的了解

Koa是express原班人⻢打造的轻量、健壮、富有表现力的nodejs框架。

使用Koa

  • koa安装
    * $ npm i koa
  • 一个简单的koa服务器
const Koa = require("koa");
//koa正常使用
let app = new Koa();
//使用  会有一个回调函数

ctx:   context对象
 app.use(async (ctx) => {
    
    
     //ctx.request === req;   ctx.response === res;
     // ctx.response.body = "hello world";

     ctx.body = "hello "
     console.log(ctx.url);
 })
  • Koa 利用中间件控制"上游",调用"下游“;
  • koa是包含一组中间件函数的对象;可以将app.use里的函数理解成中间件
  • 通过next()将控制转交给另一个中间件;
let m1 = async function(ctx, next) {
    
    
    console.log("m1");
    //ctx.state     传递数据
    //它就像一个中间间的贡献空间
    ctx.state = {
    
    
            perPage: 5,
            totalPage: "13"
        }
        //将控制权,交给下一个中间件
    next(); //  ----->m2

    // console.log("m1   end");
}
let m2 = async function(ctx, next) {
    
    
    // console.log("m2");
    console.log(ctx.state);
    ctx.state = {
    
    
        p: 1,
        id: 14,
        totalPage: 3
    }

    next(); //------->下一个中间件

    // console.log("m2   end");
}
let m3 = async function(ctx, next) {
    
    
    // console.log("m3");
    //     next();

    // console.log("m3   end");
    console.log(ctx.state);
    ctx.body = "hello";
    //状态码
    // ctx.status = 404
}

// 中间件在实际使用,全部都是模板
app.use(m1);
app.use(m2);
app.use(m3);

Koa常用中间件

Koa-router
安装

npm i koa-router -S

使用
const KOa = require("koa");
const Router = require("koa-router");

let app = new KOa();
let router = new Router();

router.get("/", async ctx => {
    
    
    //会将   /  和  /index的请求,返回同一页面
    ctx.redirect("/index");
    ctx.body = "hello world";
})

router.get("/datail", async ctx => {
    
    
    ctx.body = "详细页";
})

router.get("/getData", async ctx => {
    
    
    // let indexData = fs.readFile("index.html");

    let indexData = "w我是读取模板";
    //简写
    // ctx.body = {
    
    
    //     indexData
    // }

    ctx.render("/index2", {
    
    
        indexData
    })
})
app.use(router.routes());
app.listen(8889);

RESTful: 接口设计原则
post / get
错误做法
localhost:8000/adduser
localhost:8000/deleteuser
localhost:8000/uodateuser
localhost:8000/getuser

正确做法
localhost:8000/user 请求方式 get获取
localhost:8000/user delete 删除
localhost:8000/user put 更新
localhost:8000/user post 添加

REST设计一般符合如下条件:
程序或者应用的事物都应该被抽象为资源
每个资源对应唯一的URI(uri是统一资源标识符)
使用统一接口对资源进行操作
对资源的各种操作不会改变资源标识
所有操作都是无状态的

koa-views
  • 安装koa-views
npm i koa-views -S
  • 使用
const Views = require("koa-views");
app.use(Views(__dirname + "/views", {
    
    
    extension: "pug"
}));
router.get("/", async ctx => {
    
    
    // ctx.body = "hello world";
})
app.use(router.routes());

app.listen(8081);
koa-static
  • koa-static 是由于加载静态资源的中间件,通过他加载css、js等静态资源;
  • 安装koa-static
npm i koa-static
使用koa-static
const static = require("koa-static);
app.use(static(__dirname+"/static))//加载静态文件的目录

猜你喜欢

转载自blog.csdn.net/weixin_54645137/article/details/115206985
koa