koa use

(Post an official website , koa content is really not much, very small and lightweight)

1. What is koa?

A smaller, more expressive, more robust web framework. Using koa to write web applications, by combining different generators, 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.

Basic example:

const koa = require("koa");

const app = new koa(); // express 不用 new,是 const app = express();

app.use(async (ctx, next) => { // 为应用添加指定的中间件
    console.log(ctx.request.path); // 打印请求的 url 路径部分
    // ctx.response.body = "<b>Hello World</b>"; // 设置响应体 
    // ctx.response.body = "Hello World"; // 设置响应体
    ctx.response.body = {name: "bob"}; // 设置响应体
})

app.listen(3000); // 监听 3000 端口

2. ctx parameter

The context is created in each request, and is referenced as a receiver in the middleware, or through the this identifier, and has several important attributes on it:

  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.cookies.get(name, [options]): Get the value named name in the cookie, options is an optional parameter
  6. ctx.cookies.set(name, value, [options]): Set the value named name in the cookie, options is an optional parameter
  7. ctx.throw([status], [msg], [properties]): Throw an error containing the .status property, the default is 500. This method allows Koa to accurately respond to the processing status, for example ctx.throw(400, 'name required', { user: user });

[Note: app.context is the prototype from which ctx is created. Additional properties can be added to ctx by editing app.context, which is useful when you need to add ctx to properties or methods used throughout the application. For example, add a reference to the database to ctx]

app.context.db = db();

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

[Note: Many context accessors and methods are simply delegated to the equivalent methods corresponding to their ctx.request and ctx.response for easy access and invocation, such as ctx.type, ctx.length, ctx.body proxy The corresponding method in the response object, ctx.path, ctx.method, ctx.header proxy the corresponding method in the request object]

3. next parameter

When the next statement is executed, Koa suspends the middleware, continues to execute the next middleware that meets the request, and then returns control to the upper middleware step by step

The following example returns "Hello World" in the page. However, when the request starts, the request first passes through the x-response-time and logging middleware, and records the middleware execution start time. Control is then passed to the response middleware. When a middleware calls the next() function, the function is suspended and control is passed to the next defined middleware. After there are no more middleware executing downstream, the stack is exited and each middleware is resumed to perform its upstream behavior

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

// x-response-time

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  ctx.set('X-Response-Time', `${ms}ms`);
});

// logger

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response

app.use(async ctx => {
  ctx.body = 'Hello World';
});

app.listen(3000);

4. request object

The Koa Request object is a further abstraction and encapsulation of node's request, which provides some useful functions in daily HTTP server development. The commonly used APIs are:

  1. request.header: Get or set the request header object (equivalent to request.headers)
  2. request.method: get or set the request method
  3. request.length: Return the content length (Content-Length) of the request in the form of a number, or return undefined
  4. request.url: get or set request url address
  5. request.href: Get the complete request URL, including protocol, host and url
  6. request.path: Get the request path name, or set the request path name and keep the current query string
  7. request.querystring: Get the query parameter string (the part after ? in the url, excluding ?), or set the original query string
  8. request.search: Get the query parameter string (including ?), or set the original query string
  9. request.type: Get the request Content-Type, does not contain parameters like "charset"
  10. request.is(types…): Check whether the "Content-Type" contained in the request is the given type value. Returns undefined if there is no request body. Returns false if there is no content type, or if the match fails. Otherwise return the matching content-type
    // When Content-Type is application/json
    ctx.is('json', 'urlencoded'); // => 'json'
    ctx.is('application/json'); // => 'application/json'
    ctx.is('html', 'application/*'); // => 'application/json'
    
    ctx.is('html'); // => false
    
  11. request.charset: Get the request charset (for example "utf-8"), if not, return undefined
  12. request.query: Parse the query parameter string and return it in the form of an object. If there is no query parameter string, return an empty object, or set the query parameter string according to the given object. Note that this method does not support nested parsing
  13. request.fresh: Checks whether the request cache is "fresh" (the content has not changed). This method is used for cache coordination in If-None-Match / ETag, If-Modified-Since and Last-Modified. This method should be used when one or more of the above parameters are set in the response headers
  14. request.stale: the opposite of req.fresh
  15. request.protocol: Returns the request protocol, "https" or "http". X-Forwarded-Host is supported when app.proxy is set to true
  16. request.socket: returns the requested socket
  17. request.get(field): returns the value of the field field in the request header

5. response object

The Koa Response object is a further abstraction and encapsulation of node's response, which provides some useful functions in daily HTTP server development. Common APIs include:

  1. response.socket: Response socket (socket is socket), pointing to net.Socket instance as request.socket
  2. response.header: response header object (equivalent to response.headers)
  3. response.status: Get the response status (by default, response.status is set to 404, unlike node's res.statusCode which defaults to 200), or set the response status by a number
  4. response.message: Get the response status message (by default, response.message is associated with response.status), or set the response status message to a given value
  5. response.body: Get the response body, or set the response body (if res.status is not assigned at this time, Koa will automatically set it to 200 or 204)
  6. response.length: Returns the Content-Length of the response as a number, or derived from ctx.body, or undefined, or sets the Content-Length of the response to a given value
  7. response.set(field, value): Set the value of the response header field field to value
  8. response.append(field, value): add an additional field with the value of val
  9. response.set(fields): Use an object to set the values ​​of multiple fields in the response header at the same time
  10. response.remove(field): Remove the field filed in the response header
  11. response.type: Get the response Content-Type, does not contain parameters like "charset", or set the response Content-Type by mime type string or file extension
  12. response.redirect(url, [alt]): Execute [302] to redirect to url. If you want to modify the default [302] status code, you can execute it directly before or after redirection. If you want to modify the body, you need to execute it before redirecting
    [the string "back" is a special parameter, which provides Referrer support. When there is no Referrer, use alt or / instead]
    ctx.redirect('back');
    ctx.redirect('back', '/index.html');
    ctx.redirect('/login');
    ctx.redirect('http://google.com');
    
  13. response.headerSent: Check whether the response header has been sent, used to check whether the client is notified when an error occurs
  14. response.lastModified: If there is Last-Modified, it will be returned in the form of Date, or set Last-Modified in UTC format, which can be set using Date or date string

6. The difference between koa1, koa2 and express

  1. There are different ways to achieve asynchrony. Koa1 achieves asynchrony through generator/yield, koa2 achieves asynchrony through async/awaite, and express achieves asynchrony through callback functions.
  2. express is large and comprehensive, with most of the middleware built-in, which is more worry-free. koa2 does not bind any framework, clean and concise, small and refined, easier to customize, and has good scalability. I want to implement express in koa Many functions need to be solved with the help of third-party middleware
    insert image description here
  3. Express itself does not support the data inflow and outflow capabilities of the onion model (similar to linear), and needs to introduce other plug-ins. In koa, all processes are middleware, and the data flow follows the onion model, first in, then out, yes Organized and executed in a stack-like manner, koa data flows in and out. After next(), it will enter the next middleware and execute it, and then reverse execution from the last middleware
    const Koa = require('koa')
    const app = new Koa()
    
    const mid1 = async (ctx, next) => {
        ctx.body =  '前:' + '1\n'
        await next()
        ctx.body =   ctx.body + '后:' + '1\n'
    }
    
    const mid2 = async (ctx, next) => {
        ctx.body =    ctx.body + '前:'+ '2\n'
        await next()
        ctx.body =    ctx.body + '后:'+ '2\n'
    }
    
    const mid3 = async (ctx, next) => {
        ctx.body =  ctx.body + '前:'+  '3\n'
        await next()
        ctx.body =   ctx.body + '后:'+ '3\n'
    }
    
    app.use(mid1)
    app.use(mid2)
    app.use(mid3)
    
    app.listen(3000)
    
    // 前1
    // 前2
    // 前3
    // 后3
    // 后2
    // 后1
    
  4. koa has added a new context object, as the context object of this request, in addition to providing a large number of convenient api-assisted development, it can also save some public parameter data on it for use

Guess you like

Origin blog.csdn.net/m0_52212261/article/details/128345228