Koa2 goes from beginner to Master one

Learning document

Reference documentation

Environment building & Project creation

  • Install the Node
  • Global erection scaffoldingnpm install -g koa-generator koa-generator
  • Create a projectKoa2 Project file name
  • Enter the project installation dependenciesCD Project filename & NPM install
  • Run the projectnpm start

Project initialization dependency details

Json {"name": "demo", "version": "0.1.0", "private": true, "scripts": { "start": "node bin/www", "dev": "./node_modules/.bin/nodemon bin/www", "prd": "pm2 start bin/www", "test": "echo \"Error: no test specified\" && exit 1" }, "dependencies": { "debug": "^ 4.4.1," "koa" : "^ 2.7.0", "koa - bodyparser" : "^ 2", "koa - convert" : "^ 1.2.0", "koa - json" : "^ 2.0.2", "koa - logger" : "^ 3.2.0 koa -", "onerror" : "^ 4.1.0", "koa - the router" : "^ 7.4.0", "koa - static" : "^ 5.0.0", "koa - views" : "^ 6.2.0", "relation" : "^ 3.0.2"}, "devDependencies" : {" nodemon ":" ^ 1.19.1 "}}Copy the code
  • Debug Debugging plug-innpm install debug -S

Reference documentation

NPM document

  • Koa is used to create KOA applicationsnpm install koa -S

Reference documentation

Js const Koa = require(' Koa ') const app = new Koa() app.use() // module. Exports = appCopy the code
  • koa-bodyparser npm install koa-bodyparser -S

Parses the data in the body of the POST request and returns an empty object if not parsed. {}

Ctx. body = ctx.request.body The body data after processing is obtained through ctx.body during subsequent interface processing

Reference documentation

You can also customize the related parameter configuration, refer to the documentation

Const Koa = require(' Koa ') const app = new Koa() const bodyParser = require(' koa-bodyParser ') // Use middlewares app.use(bodyparser({ enableTypes: ['json', 'form', 'text'] }))Copy the code
  • koa-convert npm install koa-convert -S

Reference documentation

Used to switch from generator-based middleware in KOA to promise based middleware

Convert Koa’s older (0.x and 1.x) generator middleware to modern Promise middleware (2.x)

Koa1.x is implemented on a generator basis

The plug-in is installed here but not applied

  • koa-json npm install koa-json -S

Reference documentation

Used to set the json format to be returned, Spaces, whether to beautify line feeds, and so on

Const json = require('koa-json') // Use koa-json middleware app.use(json())Copy the code

Const json = require('koa-json') // Use koa-json middleware app.use(json({pretty: false}))Copy the code

  • koa-logger npm install koa-logger -S

Reference documentation

Function: Output logs

Const Koa = require(' Koa ') const app = new Koa() const logger = require('logger') app.use(logger()) // logger prints logs App.use (async (CTX, next) => {const start = new Date() await next() const ms = new Date() -start console.log(' Hello ', `${ctx.method} ${ctx.url} - ${ms}ms`) })Copy the code
  • koa-onerror npm install koa-onerror -S

Reference documentation

Purpose: Error handling

const Koa = require('koa')
const app = new Koa()
const onerror = require('koa-onerror')
onerror(app)
Copy the code
  • koa-router npm install koa-router -S

Reference documentation

routing

// demo/app.js const Koa = require('koa') const app = new Koa() const index = require('./routes/index') const users = Require ('./routes/users') // routes Implemented 'app. Use (index.routes(),' 405 Method Not Allowed 'or' 501 Not Implemented 'app. index.allowedMethods()) app.use(users.routes(), users.allowedMethods())Copy the code
// demo/routes/index.js const router = require('koa-router')() router.get('/', async (ctx, next) => { await ctx.render('index', { title: 'Hello Koa 2! ' }) }) router.get('/string', async (ctx, next) => { ctx.body = 'koa2 string' }) router.get('/json', async (ctx, next) => { ctx.body = { title: 'koa2 json' } }) module.exports = routerCopy the code
// routes/users.js const router = require('koa-router')() router.prefix('/users') // route router.get('/', function (ctx, next) { ctx.body = 'this is a users response! ' }) router.get('/bar', function (ctx, next) { ctx.body = 'this is a users/bar response' }) module.exports = routerCopy the code
  • koa-static npm install koa-static -S

Reference documentation

Function: Processes static resources

Multiple static directories can be specified

This file name is not required for external access to static resources in this folder

// Open the public folder in the root directory, Const Koa = require(' Koa ') const app = new Koa() app. Use (require(' Koa -static')(__dirname + '/public')) // App. use(require('koa-static')(__dirname + '/static')Copy the code

  • koa-views npm install koa-views -S

Reference documentation

Function: View management

Used in conjunction with the template engine

  • Pug template enginenpm install pug -S

Reference documentation

const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
app.use(views(__dirname + '/views', {
  extension: 'pug'
}))
Copy the code
  • I don’t want to use the view here, but I’ve removed the root view stuff

Deleted demo/views, js and CSS files

Modified the route of the display view

Uninstall KOA-views and PUG

npm uninstall koa-views pug
Copy the code

  • Nodemon hot updatenpm install nodemon -D

Hot update is enabled here and can be viewed in package.json

But you need to set it in conjunction with the cross-env environment variable

npm install cross-env -D

  • Development environment passesnpm run devThe project can be updated in real time by launching it, and the code can be restarted automatically after modification