1. 新建项目文件夹lazyStall文件夹

  • 右键进入vsvode
  • 新建文件index.js文件作为入口文件
  • 新建终端 npm14版本以上 当前使用版本18.14版本 输入npm init -y
  • npm init -y 创建的程序规范默认为cjs 现在要改为ESM规范 需要添加type:module
package.json
  {
     "type": "module",
     "name": "lazystall",
     "version": "1.0.0",
     "description": "",
     "main": "index.js",
     "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1"
     },
     "keywords": [],
     "author": "",
     "license": "ISC"
  }

  • 安装nodemon 热更新修改代码时可以自动刷新
  npm install --save-dev nodemon
  • 把脚本指令放到package.json文件scripts属性内
 "scripts": {
     "dev": "nodemon ./src/index.js",
     "test": "echo \"Error: no test specified\" && exit 1"
     },
  • 在index.js文件里面舒服console.log("项目启动")并输入指令并查看log
npm run dev
  • 终端输入指令安装最新koa2依赖包
npm i koa
  • index.js 实例化koa并启动项目验证洋葱模型
// 引入koa ESM规范

import Koa from 'koa'

// 设置端口号为8088

const port = 8088

/*

创建koa实例

实例化是指根据一个类创建一个对象的过程

*/

const app = new Koa()

/*

app.use()用于中间件的注册

每一个http请求进来都回按照顺序执行中间件

ctx(context)包含了当前http请求所有信息

http方法,url,header,请求参数等

*/

app.use(async (ctx, next) => {

console.log('中间件1')

await next() //若中间件调用了next(),会暂停当前中间件的执行,将控制权传递给下一个中间件

console.log('中间件2')

})

app.use(async (ctx, next) => {

console.log('中间件3')

await next()

console.log('中间件4')

})

//当中间件没有再调用next(),则不需要再将控制权传递给下一个中间件,控制权会按照相反的顺序执行

app.use(async (ctx) => {

console.log('中间件5')

ctx.body = 'hello world1'

})

/*

启动服务器并 当前服务器端口号

*/

app.listen(port, () => {

console.log(`server is running at http://localhost:${port}`)

})

项目启动后输出一次为console.log(中间件1)/console.log(中间件3)/console.log(中间件5)/console.log(中间件4)/console.log(中间件2)

安装router 输入指令

npm i @koa/router