Basic use of Koa2

1. Create a new folder

  1. First open the terminal and enter node -Vthe command to check the Node version. For the Koa2 framework, the Node version needs to be higher than7.6
  2. Use npm init -ythis command to quickly create package.jsona file
  3. npm install koaDownload the latest version koato the current project using

2. Initial use

Create app.js
insert image description here

// 创建koa对象
const Koa = require('koa')
const app = new Koa()
// 编写相应函数(中间件)
app.use((ctx, next) => {
    
    
  // await next()
  // ctx.response.type = 'text/html'
  console.log(ctx.request.url);
  ctx.response.body = '<h1>Hello, koa2----!</h1>'
})
// 3.绑定端口号3000
app.listen(3001)

Enter in the browser address bar http://127.0.0.1:3001/, that is, the operation is successful

3. Koa2 onion model (middleware)

Middleware features:
1. An Koaobject useis added to a middleware through a method;
2. A middleware is a function;
3. The execution sequence of middleware conforms to the onion model
4. Whether the inner middleware can be executed depends on whether the outer middleware is activated next函数or not. Call
5. Whether the next layer of middleware is executed depends on whether it is executed or not. 6. The time object next()
obtained by calling the next() functionPromise

insert image description here

// 创建koa对象
const Koa = require('koa')
const app = new Koa()
// 编写相应函数(中间件)
app.use((ctx, next) => {
    
    
  console.log('第一层中间件执行了----1');
  ctx.response.body = '<h1>Hello, koa2----!</h1>'
  next()
  console.log('第一层中间件执行了----2');
})
app.use(async(ctx, next) =>{
    
    
  console.log('第二层中间件执行了----1');
  const ret =await next()
  console.log(ret,'ret=====');
  console.log('第二层中间件执行了----2');
})
app.use((ctx, next) =>{
    
    
  console.log('第三层中间件执行了');
  return '第三层返回一些东西,到第二次用async await在next()接收'
})
// 3.绑定端口号3000
app.listen(3001)

Guess you like

Origin blog.csdn.net/weixin_43811753/article/details/130410077