1. Create a new folder
- First open the terminal and enter
node -V
the command to check the Node version. For the Koa2 framework, the Node version needs to be higher than7.6
- Use
npm init -y
this command to quickly createpackage.json
a file npm install koa
Download the latest versionkoa
to the current project using
2. Initial use
Create app.js
// 创建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. AnKoa
objectuse
is 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 activatednext函数
or not. Call
5. Whether the next layer of middleware is executed depends on whether it is executed or not. 6. The time objectnext()
obtained by calling the next() functionPromise
// 创建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)