What is koa2?
- koa is the next generation web development framework based on nodejs platform
- You can use koa to quickly start a web service to provide http
Feel koa2
- Create an empty folder on the desktop and generate the package.json file through npm init -y in cmd
- Install KOA npm i koa
- Install nodemon to monitor the changes of js files (it is recommended to install nodemon globally first)
Use koa2 to write service programs
- Import the installed package of koa2
- Instantiate app object
- Writing Middleware - middleware is actually a function
- Start service listening 3000 port
-
// 1. Introduce koa package. Note that mac and liunx must be case sensitive when importing packages. windows is not case sensitive const Koa = require('koa') // 2. Instantiate app object const app = new Koa() // 3. Use use to register middleware. ctx represents the context of http request. ctx is the abbreviation of context app.use((ctx) => {ctx.body = 'hello koa'}) // 4. Start the service and listen to port 3000 app.listen(3000,() => { console.log('server is running on http://localhost:3000'); })
We recommend a special http client -- postman
Use nodemon to start, because nodemon can listen for changes to js files
Normal startup interface
When the js file is modified
When the startup is complete, we can use postman to verify
The result returned after startup is the data in ctxbody
This is koa2's first experience
Basic concepts of Middleware
- A functionally independent function that executes between a request and a response
- The front end sends a request to the back end. The back end processes the data one by one, and finally integrates the data and returns it to the front end
- It's like a batch of raw materials entering the processing plant, passing through an assembly line and becoming products for consumers
- Middleware is the workers who make up this assembly line, and everyone performs their own duties.
- Code demonstration
// 1. Introduce koa package const Koa = require('koa') // 2. Instantiate app const app = new Koa() // 3. Three middleware are written, and each middleware is a function app.use((ctx, next) => { console.log('Processing head'); next() }).use((ctx, next) => { console.log('Dealing with the body'); next() }).use(ctx => { ctx.body = 'Processing complete' }) // 4. Start service app.listen(3000, () => { console.log('server is running on http://localhost:3000'); })
6.use is used three times. The first two uses process the data. After the current two uses are executed, use the next method to notify the next use to know that the last use completes the data processing
Onion ring model
After walking one way, return to the original way
Asynchronous operation
async keyword: you can encapsulate the return object of a function as a promise object
When there is no async modifier
When there is async modification
Since it is a promise object, you can use the then method to get the data
await keyword
Firstly, the await keyword cannot be used alone. If you want to use await, the function must be decorated with async
await is followed by a promise object, and the expression returns the promise result
async function fn(){ const p = new Promise(resolve => { // When the resolve method is called, the result of p is 123 and the status is fully resolve(123) }) console.log(await p); } fn()
koa processes synchronous data
// 1. Introduce koa2 const Koa = require('koa') // 2. Instantiate app const app = new Koa() // 3. Write Middleware app.use((ctx,next)=>{ ctx.message = "kkk" next() ctx.body = ctx.message }).use((ctx,next)=>{ ctx.message += 'ooo' next() }).use(ctx=>{ ctx.message += 'aaa' }) // 4. Start service app.listen(3000,()=>{ console.log('server is running on http://localhost:3000'); })
koa processing asynchronous data
// 1. Introduce koa2 const Koa = require('koa') // 2. Instantiate app const app = new Koa() // 3. Write Middleware app.use(async (ctx,next)=>{ ctx.message = "kkk" await next() ctx.body = ctx.message }).use(async (ctx,next)=>{ ctx.message += 'ooo' await next() }).use(async ctx=>{ const res = await Promise.resolve('aaa') ctx.message += res }) // 4. Start service app.listen(3000,()=>{ console.log('server is running on http://localhost:3000'); })
koa-router
Back end Routing: different contents are returned according to different request method s and request address URLs
// 1. Introduce koa2 const Koa = require('koa') // 2. Instantiate app const app = new Koa() // 3. Introducing koa router const Router = require('koa-router') // Instantiate router object const router = new Router() router.get('/',(ctx)=>{ ctx.body = 'This is the registration page' }) router.get('/users',(ctx)=>{ ctx.body = 'This is the user page' }) router.post('/users',(ctx)=>{ ctx.body = 'Create user' }) // 4. Register Middleware app.use(router.routes()) // 5. Start service app.listen(3000,()=>{ console.log('server is running on http://localhost:3000'); })
Request parameter resolution
Two forms of parsing url parameters query and params
// 1. Introduce koa2 const Koa = require('koa') // 2. Instantiate app const app = new Koa() // 3. Introducing koa router const Router = require('koa-router') // Instantiate router object const router = new Router({prefix: '/users'}) // Define a constant db to represent the database const db = [ {id: 1,name: "zs",age:18}, {id: 2,name: "ls",age:28}, {id: 3,name: "ww",age:38} ] // Write routing rules // get /users gets all user information and returns an object router.get('/:id',(ctx)=>{ const id = ctx.params.id const res = db.filter((item) => item.id == id) if(!res[0])ctx.throw(404) ctx.body = res[0] }) router.get('/',(ctx)=>{ const par = ctx.query console.log(par.start,par.end); let res = db.filter(item => item.age >= par.start && item.age <= par.end) console.log(res); res.length == 0 ? ctx.throw(404) : ctx.body = res console.log(res.length); }) router.post('/',(ctx)=>{ ctx.body = db }) // 4. Register Middleware app.use(router.routes()) // 5. Start service app.listen(3000,()=>{ console.log('server is running on http://localhost:3000'); })
Analysis of body parameters
- Install the middleware of KOA body
- register
- use