0. Prepare

  1. Check the Node version. Koa requires a version 7.6 or later

    node -v
    Copy the code

Basic use

1.1 Setting up the HTTP Server

Using KOA to set up an HTTP server is as simple as following three steps

//demo01.js
const Koa = require('koa')
const app = new Koa()

app.listen(3000)
Copy the code

Then run the file using the node command

node buildHttp.js
Copy the code

Open the browser and we type http://loaclhost:3000 and the page says Not Found because we didn’t tell Koa what to display

1.2 the Context object

Koa provides a Context object that represents the Context of a conversation (including HTTP request objects and response objects) and manipulates this object to control what is returned to the user

The context.response. body property is the content sent to the user

//demo02.js
const Koa = require('koa')
const app = new Koa()

var main = ctx= > {
    ctx.response.body = 'hello world'
}

app.use(main)
app.listen(3000)
Copy the code

The main method is used to set the response content, and then the app.use method uses that function

Run the file using the node command to access the browser again

1.3 Type of HTTP Response

The default return type for Koa is text/plain, so we can take a look at what type of data the client wants to Accept by ctx.request (according to the Accept field in the HTTP request), and then specify the return value type by ctx.response.type

// demo03.js
  
const Koa = require('koa');
const app = new Koa();

const main = ctx= > {
  if (ctx.request.accepts('xml')) {
    ctx.response.type = 'xml';
    ctx.response.body = '<data>Hello World</data>';
  } else if (ctx.request.accepts('json')) {
    ctx.response.type = 'json';
    ctx.response.body = { data: 'Hello World' };
  } else if (ctx.request.accepts('html')) {
    ctx.response.type = 'html';
    ctx.response.body = '<p>Hello World</p>';
  } else {
    ctx.response.type = 'text';
    ctx.response.body = 'Hello World'; }}; app.use(main); app.listen(3000);
Copy the code

1.4 Web template

In the actual development process, the web page returned to the user is usually written as a template file. Koa can get the template first and then return the template to the user

// demo04.js
const Koa = require('koa')
const app = new Koa()
const fs = require('fs')

var main = ctx= > {
    ctx.response.type = 'html'
    ctx.response.body = fs.createReadStream('./views/template.html')
}

app.use(main)
app.listen(3000)
Copy the code

2. The routing

2.1 Native Route

Native route is the route written by us. Through the judgment of URL, different content is returned to the user. The specific implementation is as follows

// demo05.js
const Koa = require('koa')
const app = new Koa()

var main = ctx= > {
    if(ctx.request.path == '/'){
        ctx.response.type = 'html'
        ctx.response.body = 'home page'
    }else if(ctx.request.path === '/about'){
        ctx.response.type = 'html'
        ctx.response.body = '<h1>about page</h1>'
    }else{
        ctx.response.type = 'html'
        ctx.response.body = '<h1>no set url resource</h1>'
    }
}

app.use(main)

app.listen(3000)
Copy the code

2.2 koa – the router module

Native routes are not very convenient to use, so we encapsulated the KOA-Route template

// demo06.js

const Koa = require('koa')
const app = new Koa()
const route = require('koa-route')

var home = ctx= > {
    ctx.response.type = 'html'
    ctx.response.body = `<a href='#'>Home page</a>`
}

var about = ctx= > {
    ctx.response.type = 'html'
    ctx.response.body = `<a href='#'>About page</a>`
}

app.use(route.get('/',home))
app.use(route.get('/about',about))

app.listen(3000)
Copy the code
  • In the code above,/The path handler is home,/aboutThe path handler is about

2.3 Static Resources

If the site provides static resources (images, fonts, styles, scripts), writing routes for them is cumbersome and unnecessary

The KOA-Static module encapsulates this part of the request

//demo07.js
const Koa = require('koa')
const app = new Koa()
const serve = require('koa-static')
const path = require('path')

const main = serve(path.join(__dirname))

app.use(main)


app.listen(3000)
Copy the code
  • After setting this parameter, you can directly enter the static resource file name in the URL address for access

2.4 the redirection

In some cases, the server needs to be redirected,

The ctx.Response.redirect () method emits a 302 redirect that directs the user to another route

// demo08.js
const Koa = require('koa')
const app = new Koa()
const route = require('koa-route')

var home = ctx= > {
    ctx.response.type = 'html'
    ctx.response.body = `<a href='#'>Home page</a>`
}

var about = ctx= > {
    ctx.response.type = 'html'
    ctx.response.body = `<a href='#'>About page</a>`
}

var redict = ctx= > {
    ctx.response.redirect('/')
}

app.use(route.get('/',home))
app.use(route.get('/about',about))
app.use(route.get('/redict',redict))

app.listen(3000)
Copy the code

Three, middleware

3.1 the logger function

The biggest feature of KOA, and one of the most important designs, is middleware.

Take a look at the following example: implementing the log printing function,

// demo09.js
const Koa = require('koa')
const app = new Koa()

var main = ctx= > {
    console.log(`The ${Date.now()}--${ctx.request.method}--${ctx.request.url}`)
    ctx.response.body = 'hello world'
}

app.use(main)
app.listen(3000)
Copy the code

3.2 Concepts of middleware

Based on the example above, we can separate the logging function into a separate function

Separate functions that are pulled out are called middleware

** Stands between Http Request and Http Response, is used to implement some intermediate function, and then uses the app.use method to use middleware

** Parameters: ** Each middleware accepts two parameters by default

  • CTX: context object
  • Next: The second argument is the next function. Simply call the next function and hand execution over to the next middleware
const logger = (ctx,next) => {
	 console.log(`${Date.now()}--${ctx.request.method}--${ctx.request.url}`)
	 next()
}

app.use(logger)
Copy the code

3.3 Middleware Stack

Multiple middleware will be arranged into a stack structure and executed in a first-in, last-out order

  • The order of execution is as follows

    1.The outermost middleware executes first.2.Call the next function, passing execution to the next middleware3..4.The innermost middleware executes last5.When execution is complete, execution is handed back to the middleware at the next level6..7.After the outermost middleware regains execution, the code after the next function is executedCopy the code
  • The sample

    // demo10.js
    const Koa = require('koa')
    const app = new Koa()
    
    const one = (ctx,next) = > {
        console.log('>> one')
        next()
        console.log('<< one')}const two = (ctx,next) = > {
        console.log('>> two')
        next()
        console.log('<< two')}const three = (ctx,next) = > {
        console.log('>> three')
        next()
        console.log('<< three')
    }
    
    app.use(one)
    app.use(two)
    app.use(three)
    
    app.listen(3000)
    Copy the code
  • The results

    >> one
    >> two
    >> three
    << three
    << two
    << one
    Copy the code

3.4 Asynchronous intermediate stack

If there are asynchronous operations, the middleware must write async functions

// demo11.js
const Koa = require('koa')
const app = new Koa()
const fs = require('fs')

var main = async function(ctx,next){
    ctx.response.type = 'html'
    ctx.response.body = await fs.readFileSync('./views/template.html'.'utf-8')
}

app.use(main)

app.listen(3000)
Copy the code

3.5 Middleware composition

The KOA-compose module can compose multiple middleware pieces into one

// demo12.js
const Koa = require('koa')
const app = new Koa()
const compose = require('koa-compose')

const logger = (ctx,next) = > {
    console.log(`The ${Date.now()}${ctx.request.method}${ctx.request.url}`)
    next()
}

const main = (ctx,next) = > {
    ctx.response.body =  'hello world'
}

const middleWares = compose([logger,main])
app.use(middleWares)
app.listen(3000)
Copy the code

Note: This article refers to Ruan Yifeng: KOA Framework tutorial