Development framework based on node.js-Koa

1. Introduction

Koa is  a next-generation web development framework based on the nodeJs platform, built by the original team behind Express, and is committed to becoming a smaller, more expressive, and more robust web framework. Using koa to write web applications, by combining different generators, you can avoid repeated and tedious nesting of callback functions, and greatly improve the efficiency of error handling. Koa does not bind any middleware in the kernel method, it only provides a lightweight and elegant function library, which makes writing web applications handy. There are currently two major versions 1.x and 2.x. The 2.x version uses the async await syntax sugar supported after Node.js v7.6.0, providing a more elegant asynchronous programming model.

2. The core concept of Koa

What exactly does Koa do? The most important and core thing in Koa is to realize the processing of the http protocol. It has three major core concepts:

  1. Koa Application: main program
  2. Context: context
  3. Request, Response: request and response

Three, basic usage

【1】Preparation


// 1.Koa必须使用7.6以上的node版本,检查node版本,低于要求的话就升级node
$ node -v 

// 2.创建一个 my_koa 文件夹,生成package.json文件
$ npm init -y

// 3.安装koa依赖
$ npm install --save koa

[2] Write code

Create an index.js entry file in the my_koa folder, and then we use koa to set up an http service

// index.js文件
const Koa = require('Koa');  // 引入Koa
const app = new Koa();  // 创建Koa实例,定义Application

// 使用use方法来处理上下文
app.use(async ctx => {  
  // ctx是包含整个应用的上下文,可以对用户的请求做一些处理
  ctx.body = 'hello, World!'
});

app.listen(3000);  // 设置端口号,让Koa应用运行在3000端口上

After writing the above code in the index.js file, open the terminal in the file directory and enter node index.js to run the file.

Then open the browser and enter: localhost:3000, you can see the results we output

      

Four, Application (application)

A Koa application is an object containing a set of middleware functions, which is organized and executed in a stack-like manner. Koa is similar to many other middleware systems you may have encountered.

[1] app.listen() : Bind a port server as the program entry, and multiple can be bound. The following is a useless Koa application that is bound to the  3000 port

const Koa = require('koa');
const app = new Koa();
app.listen(3000); 

// app.listen(3000)是以下方法的语法糖

const http = require('http');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);

[2] app.use(function) : add the given middleware method to this application, app.use() returns this, so it can be expressed in chain

app.use(someMiddleware)
app.use(someOtherMiddleware)
app.listen(3000)

// 等同于

app.use(someMiddleware).use(someOtherMiddleware).listen(3000)

[3] app.keys=: set the signed cookie key

app.keys = ['im a newer secret', 'i like turtle'];
app.keys = new KeyGrip(['im a newer secret', 'i like turtle'], 'sha256');

[4] app.context: the prototype from which ctx is created. You can add other attributes for ctx by editing app.context    

app.context.db = db();

app.use(async ctx => {
  console.log(ctx.db);
});

[5] Error handling: add an "error" event listener

app.on('error', (err, ctx) => {
  log.error(err, ctx)
});

[6] next(): The function pauses and passes control to the next middleware defined

const Koa = require('Koa');  // 引入Koa
const app = new Koa();  // 创建Koa实例,定义Application

const one = (ctx, next) => {
    console.log('进 one');
    next();
    console.log('出 one');
}
const two = (ctx, next) => {
    console.log('进 two');
    next();
    console.log('出 two');
}
const three = (ctx, next) => {
    console.log('进 three');
    next();
    console.log('出 three');
}

app.use(one);
app.use(two);
app.use(three)
app.listen(3000)

Five, context (context)

Koa provides a Context object, which represents the context of a conversation. The Context object encapsulates the node's HTTP request (request) object and HTTP response (response) object into a single object. By processing this object, you can control the content returned to the user.

[1] Context specific methods

  1. ctx.req: node's request object
  2. ctx.res: node's response object
  3. ctx.request: koa's request object
  4. ctx.response: koa's response object
  5. ctx.state: Recommended namespace, used to pass information and your front-end view through middleware
  6. ctx.app: application instance reference
  7. ctx.cookies.get(name, [options]):获取cookie
  8. ctx.cookies.set(name, value, [options]):设置cookie
  9. ctx.throw([status], [msg], [properties]): throw an exception
  10. ctx.assert(value, [status], [msg], [properties]): throws an error

Six, Request (request)

The Koa Request object is an abstraction on top of node's native request object and provides many functions useful for HTTP server development.

  1. request.header: request header object, which can be set and assigned (request.header=xxx)
  2. request.headers: request header object, alias is request.header, can be set and assigned (request.headers=xxx)
  3. request.method: request method, you can set assignment (request.method=xxx)
  4. request.length: Returns the requested Content-Length as a number, or undefined
  5. request.url: Get the request URL, you can set the request URL, useful for url rewriting (request.url=xxx)
  6. request.originalUrl: Get the original URL of the request
  7. request.origin: Get the source of the URL, including protocol and host
  8. request.href: Get the complete request URL, including protocol, host and url
  9. request.path: Get the request path name, you can set the value, and retain the query string when it exists (request.path=xxx)
  10. request.querystring: According to? to get the original query string, you can set the original query string (request.querystring=xxx)
  11. request.search: Use? to get the original query string, you can set the original query string (request.search=xxx)
  12. request.host: Get the host if it exists

  13. request.hostname: get the hostname if it exists

  14. request.URL: Get the URL object parsed by WHATWG

  15. request.type: Get the Content-Type of the request, excluding "charset" and other parameters

  16. request.charset: Get the requested character set when it exists, or undefined

  17. request.query: Get the parsed query string, when there is no query string, return an empty object, you can set the assignment (request.query=xxx)

  18. request.fresh: Check whether the request cache is "fresh", that is, the content has not changed. This method is used for caching negotiation between If-None-Match / ETag, and If-Modified-Since and Last-Modified. It should be quoted after setting one or more of these response headers

  19. request.stale: the opposite of request.fresh

  20. request.protocol: return the request protocol, "https" or "http"

  21. request.secure: Use ctx.protocol == "https" to check whether the request is sent via TLS

  22. request.ip: request remote address

Seven, Response (response)

The Koa  Response object is an abstraction on top of node's native response object and provides many functions useful for HTTP server development.

  1. response.header: response header object
  2. response.headers: response header object, alias is response.header
  3. response.socket: response socket
  4. response.status: Get the response status. By default, response.status is set to 404 instead of 200 as the node's res.statusCode, and the response status is set by the numeric code (response.status=xxx)
  5. response.message: Get the response status message. By default, response.message is associated with response.status, and the response status message can be set to a given value (response.message=xxx)
  6. response.length: Return the Content-Length of the response as a number, or deduced from ctx.body, or undefined, you can set the Content-Length of the response to a given value (response.length=xxx)
  7. response.body: Get the response body, you can set the response body to string write, Buffer write, Stream pipeline, Object || Array JSON-stringification, null response with no content
  8. response.type: Get the response Content-Type, excluding "charset" and other parameters, you can set the response Content-Type through mime string or file extension (response.type=xxx)

[1] Types of HTTP Response

Koa's default return type is text/plain (plain text). If you want to return other types of content, you can use ctx.request.accepts to determine what data the client wants to accept (according to the Accept field of the HTTP Request). Then use ctx.response.type to specify the return type.

const Koa = require('koa')
const app = new Koa()

const main = (ctx, next) => {
  if (ctx.request.accepts('json')) {
    ctx.response.type = 'json';
    ctx.response.body = { data: 'Hello World' };
  } else if (ctx.request.accepts('html')) {
    ctx.response.type = 'html';
    ctx.response.body = '<p>Hello World</p>';
  } else if (ctx.request.accepts('xml')) {
    ctx.response.type = 'xml';
    ctx.response.body = '<data>Hello World</data>';
  } else {
    ctx.response.type = 'text';
    ctx.response.body = 'Hello World';
  };
}; //直接运行页面中会显示json格式,因为我们没有设置请求头,所以每一种格式都是ok的。   

app.use(main) //app.use(function)用来加载中间件。
app.listen(3000)

8. Middleware

【1 Introduction

The biggest feature of koa is the unique middleware process control, which is the famous "onion model". We can clearly see that a request passes through the middleware layer by layer from the outside to the inside, and from the inside to the response when responding. Go through the middleware layer by layer. Just like when we insert a toothpick into an onion, the toothpick passes through layers of onion skin from the outside to the inside to reach the "onion heart". When we pull it out, the toothpick passes through a layer of onion skin from the inside to the outside.

 

【2】Case

Basically, all the functions of Koa are implemented through middleware. Each middleware accepts two parameters by default. The first parameter is the Context object, and the second parameter is the next function. As long as the next function is called, the execution right can be transferred to the next middleware. If the next function is not called inside the middleware, the execution right will not be passed on. The middleware1, middleware2, and middleware3 functions in the following code are called "middleware" (middleware) because they are in the middle of HTTP Request and HTTP Response, and are used to implement some intermediate functions. app.use() is used to load middleware

const Koa = require('Koa');
const app = new Koa();

// 定义三个中间件的方法:middleware1、middleware2、middleware3,next()方法代表执行完当前中间件方法后,继续执行后面的方法
const middleware1 = function async(ctx, next) {
  console.log('这是第一条middleware');
  next();
  console.log('这是第一条next之后的打印')
}
const middleware2 = function async(ctx, next) {
  console.log('这是第二条middleware');
  next();
  console.log('这是第二条next之后的打印')
}
const middleware3 = function async(ctx, next) {
  console.log('这是第三条middleware');
  next();
  console.log('这是第三条next之后的打印')
}

// 使用中间件方法
app.use(middleware1)
app.use(middleware2)
app.use(middleware3)

app.listen(5000)

[3] Middleware stack

Multiple middleware will form a middle stack, which will be executed in the order of "first-in-last-out"

  1. app.use() is executed sequentially, which middleware is referenced first, and the method of which middleware will be executed first

  2. When encountering next(), Koa will hand over the current middleware to the next middleware for processing

  3. If next() is not defined in a method, Koa will terminate the request by default and return the data

  4. If there is code after next(), Koa will wait for the entire application to be called in the order of app.use(), and then come back to execute the code after next() in reverse, which is the first-in-last-out just mentioned.

Nine, Koa-router (routing)

Websites generally have multiple pages. When we request different apis or different paths, we have to execute different methods and return different results. At this time, we have to use Koa's middleware Koa-router to handle it.

[1] Anthropomorphic Koa-router

 npm install -S koa-router

【2】Case

const Koa = require('Koa');
const Router = require('koa-router');  // 引用koa-router
const app = new Koa();
const router = new Router();

// 定义get请求
// home是我们定义的访问路径:localhost:8000/home
router.get('/home', ctx => {
  // 这个区域是中间件要去处理的上下文方法
  ctx.body = '这是主页'
})

router.get('/detail', ctx => {
    ctx.body = '这是详情页'
})

// app.use(router.routes()) 是把上面定义的路由里面的方法添加到Koa应用中
// allowedMethods方法可以把它看做一个拦截器,可以拦截一些我们应用没有定义的请求,然后返回相应的错误信息

app.use(router.routes()).use(router.allowedMethods())

app.listen(4000);  // 设置端口号,让Koa应用运行4000端口上;

// 在浏览器访问 localhost:8000/home 输出了"这是主页"
// 在浏览器访问 localhost:8000/detail 输出了"这是详情页"

10. Reference link

https://koa.bootcss.com/

http://www.ruanyifeng.com/blog/2017/08/koa.html

 

Articles are continuously updated every week. You can search for " Front-end Collection  " on WeChat to  read it for the first time, and reply to [ Video ] [ Book ] to receive 200G video materials and 30 PDF book materials

 

 

Guess you like

Origin blog.csdn.net/qq_38128179/article/details/112648175