- Koa2 Write basic Back-end interface (1)
- Koa2 Writing basic Back-end interface (2)
The middleware
If the data is understood as a product on an assembly line, the middleware is like a worker on the assembly line, who can perform some processing or other operations on the product (data) and let it continue to flow after processing.
It’s hard to avoid Koa2 without its onion ring model middleware, as anyone who knows Koa2 has seen this diagram before.
Its data flows from the outside in and then from the inside out. Install KOA to run a simple server with code to see
const Koa = require('koa');
const app = new Koa();
const PORT = 3000;
// app.use Enables middleware
app.use(async (ctx, next) => {
console.log(1)
await next()
console.log(6)}); app.use(async (ctx, next) => {
console.log(2)
await next() // If you comment this line, then print 1, 2, 5, 6
console.log(5)}); app.use(async (ctx, next) => {
console.log(3)
await next()
console.log(4)}); app.listen(PORT,() = > {
console.log(`server is running at http://localhost:${PORT}`)});// Open the page and print 1, 2, 3, 4, 5, 6
Copy the code
The middleware function takes two parameters, usually named CTX and next. Next is a method that performs a passing function. When next() is encountered, the code below next() is skipped and the next middleware is executed. At the code level, it’s called from top to bottom and then from bottom to top.
Note: Because middleware calls are passed through layers, the order in which the middleware is executed is important
example
There are many uses of middleware, such as the previous Koa2 write basic back-end interface (2) in the registration interface each response to write this will be very troublesome, can do a unified response middleware
ctx.body = {
code: 200.message: 'Registration successful',}Copy the code
Use ((CTX,next)=>{})) in a separate file, leaving the export to import calls
The main idea is to mount the response information and data to CTX, and the middleware can get the data processed into the desired format
// middleware.js
const handleResponse = ctx= > {
ctx.type = 'application/json'
ctx.body = {
code: 200.message: ctx.msg || 'success'.data: ctx.result || null,}}...// Enable middleware in app.js. app.use(handleResponse)// This middleware is best left at the end, as this is the response processing to a user request, which is basically the last level./ / use.const res = await Services.getUserList()
ctx.msg = 'Request successful'
ctx.result = res
...
Copy the code
Other middleware can also be configured, such as log printing, authentication, unified error handling, and so on