1. Introduction of Koa
Koa was built by the original Express team to be a smaller, more expressive, and more robust Web framework. Composing web applications using KOA eliminates repetitive and tedious nesting of callback functions and greatly improves error handling efficiency by combining different generators. Koa doesn’t bundle any middleware into kernel methods, it just provides a lightweight and elegant library of functions that makes writing Web applications a breeze
1.1 smaller
Koa is smaller (more than 500 lines) and lighter. Middleware needs to be downloaded separately for development. Express has a lot of built-in middleware and is highly integrated.
1.2 Expressive
The less code you have to write, the easier it is to maintain and debug. High readability, easier for compilers and people to understand.
1.3 more robust
Fault tolerance ability, easy to handle exceptions, procedures will not hang up, a good throw exceptions.
2. Middleware mechanisms
The focus of learning Koa is to understand the implementation principle of middleware and have a better understanding of the subsequent reference to third-party library middleware.
Koa’s application is essentially an object containing a set of middleware functions that are loaded with the middleware via the app.use function (which also has import order requirements). This function takes two parameters: context refers to the context object, which encapsulates some properties; Next is used to hand over the execution of the middleware to the downstream middleware. In the current middleware, the code after next() is suspended until the last middleware completes execution, and then the code of the next value week in each middleware is executed from bottom to top, similar to the advance and then out of the stack. This model is called the Onion Ring model.
Simple understanding of middleware, I think is symmetric on both sides, for example: there is an array, odd or even.
const arr = [1, 2, 3, 2, 1]
Copy the code
The program executes from the right, where 1 is code in middleware, and 2, 3. It’s just that between the 1’s and the 1’s there’s a next that points to 2 and the 2’s there’s a next that points to 3. Next (), however, returns to the current middleware (😂) as follows:
// #1 app.use(async (CTX, next)=>{console.log(1) await next(); console.log(1) }); // #2 app.use(async (ctx, next) => { console.log(2) await next(); console.log(2) }) app.use(async (ctx, next) => { console.log(3) })Copy the code
3. REST
3.1 introduction
REST is a style, a style of software architecture for the World Wide Web, for creating web services. REST does not stand for REST, but stands for Representational State Transfer, or Representational State Transfer.
- The presentation layer
For example, the text can be displayed in TXT format, JSON format or binary format.
- state
The state can be changed by using put or delete.
- conversion
Data is transmitted between client and server through HTTP protocol.
3.2 Six Limitations of REST
- Client-server (CS architecture)
- Separation of concerns: the server focuses on data processing, adding, deleting, modifying and checking; The client focuses on the interaction and user experience of the page.
- Simplicity: The old server still needs to render pages, MVC mode, now only need to focus on data, reduce code
- Portability: pages can be easily moved to other platforms, a set of code, the interface is no problem.
- Stateless
- Simplicity: All user session information (user information) is stored in a local cache on the client. Records do not need to be stored by the server
- Visibility: The client must include all information in each request and cannot rely on context information
- Reliability: The front and back ends are completely dependent on the interface, which is relatively independent and stable
- Cache
- All server responses should be marked as cacheable or not cacheable (cache-control)
- Reduced front and back end interactions, improved performance (
js
File,css
Files can be cached locally.
- Uniform Interface
- Interface design as unified as possible, improve the simplicity, visibility (simple, easy to learn, easy to maintain)
- Interface and implementation decoupling, so that the front and back end can be independent development iteration (developers do not need to be together, there is a computer to rely on documents can achieve rapid development)
- Layered System
- Each layer only knows the adjacent layer, and the hidden layer is not known (the front end only knows the interface, not the possible proxy server behind).
- Other layers: security, load balancing (traffic distribution), cache layer, etc
- Code On Demand (optional)
- The client can download the code from the running server (e.g
js
, the use ofeval
Execute) - Common unchangeable code is placed on the server, reducing some functionality and simplifying the client
- The client can download the code from the running server (e.g
3.3 Unified Port Restrictions
- Resource identification
- A resource is anything that can be named, such as a user, a comment
- Each resource can be achieved by URI unique identifier https://api/github.com/users https://api/github.com/users/day
- Express operation resources
- The client cannot directly operate server resources
json
operation
- Self-describing information
- Each message (request or response) must provide enough information for the recipient to understand
- Media type (Application/JSON)
- Make proper use of HTTP, get, POST, delete, etc
- Cache or not: cache-control
- Text links are used to jump to web pages
3.4 REST Design Specifications
- What does it look like
- The basic
URI
Format, such ashttps://api.github.com/users
- standard
http
Methods, such asget, post, put, patch, delete
- The type of data media to be transmitted
JSON
- Conform to the
REST
architecture-styleapi
- Get /users: Obtains the user list
- Get /users/day Obtains user details
- Delete the delete users / 1
id
为1
The user - Put/patch users update / 1
id
为1
The user’s information
Differences between PUT and Patch: Patch is partially updated, and PUT is replaced
- Response design specification
-
Query (background is responsible for receiving parameters and returning data)
-
Paging (a type of query), when a long list, optimized page display, paging return
-
Field filtering (a type of query). If the front end does not need to return the data, the specified field is returned to reduce the amount of data
-
Status code
- 200 – Request successful
- 301 – Resources (web pages, etc.) are permanently transferred to another URL.
- 404 – Requested resource (web page, etc.) does not exist
- 500 – Internal server error
-
Error handling
- The output
JSON
Format error message. If the status code is 4XX or 5XX, an error message should be returned to the user. In general, the information returned will beerror
As the key name, the error message as the key value
- The output
-
security
- https
- Authentication, some pages need to be logged in to view
- Limit current and prevent brush (make an intermediate layer)
http
With the headlimit
Field, record the number of requests, if exceeded, an error. You can also prompt for more limiting values after logging in
-
Developer-friendly – Provides interface documentation
4. Reference materials
- Understanding RESTful Architecture
- Node.js development imitation Zhihu server in-depth understanding of RESTful API