Analysis of the controller in Koa2

controller

what is a controller

拿到路由分配的任务,并执行

The function of routing is to assign different tasks according to different urls.

The controller is to get the task assigned by the route and execute it. It is a middleware registered in the route.

So in koa, the controller is also a middleware.

Why use a controller

  • Get HTTP request parameters
  • Handle business logic

Get HTTP request parameters

  • Query String, such as?kw=html
  • Router Params,如 /users/:id
  • Body, such as {name: "Li Lei"}
  • Header,如 Accept、Cookie

send HTTP response

  • Send Status, such as 200/400, etc.
  • Send Body, here is the returned content, such as {name: "test"}, what is returned in restfulapi is usually json, but traditional web development will also return html
  • Send Header, such as Allow (represents the allowed HTTP method), Content-Type (tells the client which method should be used to parse the returned format, restful api is often json)

Best Practices for Writing Controllers

  • The controller for each resource is placed in a different file
  • Try to use the form of class + class method to write the controller
  • strict error handling

For more exciting content, please search for " " on WeChat前端爱好者 , and click me to view .

Write the controller

Create app->controllers文件夹a storage controller.

控制器本质是中间件,中间件本质是函数,为了更合理组织这些控制器,最好采用类+类方法的形式进行编写。

Take the user controller users.js as an example


// 用户控制器users.js
const db = [{ name: "test" }]

class UsersCtl {
    //获取用户列表
    find(ctx) {
        ctx.body = db;
    }

    //获取特定用户
    findById(ctx) {
        ctx.body = db[ctx.params.id1];
    }

    //创建用户
    create(ctx) {
        db.push(ctx.request.body);
        ctx.body = ctx.request.body;
    }

    //更新用户
    update(ctx) {
        db[ctx.params.id1] = ctx.request.body;
        ctx.body = ctx.request.body;
    }
    
    //删除用户
    delete(ctx) {
        db.splice(ctx.params.id * 1, 1);
        ctx.status = 204
    }
}

// 导出实例化的控制器
module.exports = new UsersCtl();

Guess you like

Origin blog.csdn.net/BradenHan/article/details/130857140