1. The first installationkoa-router

npm install koa-router --save-dev
Copy the code

2. Use

const Router = require('koa-router');
const router = new Router();
// Start the route
app.use(router.routes()).use(router.allowedMethods())
Copy the code

3. Define routes

router.post('/home'.async ctx => {
	ctx.body = 'Hello Router';
})

router.get('/list'.async ctx => {
	ctx.body = 'Hello Router';
})
Copy the code

4. Obtain request data

  1. GET the value

In Koa, GET values are received through request in two ways: Query and QueryString

Query: Returns a parameter object. {name: ‘jack’, age: 12} QueryString: returns a request string. name=jack&age=12

Query and QueryString can be obtained from request or directly from CTX.

let request = ctx.request;
let query = request.query;
let querystring = request.querystring;

// Get CTX directly
ctx.query
ctx.querystring
Copy the code

2. POST by value

Values passed by POST can be wrapped by native Node or received by a third-party module.

  • Custom encapsulation
const querystring = require('querystring');

module.exports = ctx= > {
    return new Promise((resolve, reject) = > {
        try {
            let data = ' ';

            // ctx.req is actually req in a native node
            ctx.req.on('data', (chunk) => {
                data += chunk;
            })

            ctx.req.on('end', () => { data = querystring.parse(data); resolve(data); })}catch(err) { reject(err); }})}Copy the code
  • Use the KOA-BodyParser module
const bodyParser = require('koa-bodyparser');
app.use(bodyParser());

/ / to get
ctx.request.body
Copy the code

Complete sample

Refer to the link: www.jianshu.com/p/e6aec8bcd…