First, their own handwriting to achieve a simple KOA routing system

Koa itself is a framework under a high-level application framework, so a lot of things are streamlined, we need to introduce our own plug-ins as needed, there is no routing system itself. Itself to do routing boot, you can simply do logical processing.

If you want to return something to the client, just pass it directly to ctx.body. Koa does the serialization for us automatically.

Two, koA-Router plug-in, three steps to achieve a simple route

Koa-router:github.com/ZijianHe/ko…

var Koa = require('koa');
var Router = require('koa-router');

// Step 1: instantiate the KOa-router
var app = new Koa();
var router = new Router();

// Step 2: Add a route and a handler to the koa-Router object
router.get('/'.(ctx, next) = > {
  // This function will be registered as middleware later, so it is safe to use CTX and next
  // ctx.router available
});

// Step 3: Register all the routing and processing functions of the KOa-Router object as middleware
app
  .use(router.routes())
  .use(router.allowedMethods());
Copy the code

Three, common types of request processing

// Modify as needed
router
  .get('/'.(ctx, next) = > {
    ctx.body = 'Hello World! ';
  })
  .post('/users'.(ctx, next) = > {
    // ...
  })
  .put('/users/:id'.(ctx, next) = > {
    // ...
  })
  .del('/users/:id'.(ctx, next) = > {
    // ...
  })
  .all('/users/:id'.(ctx, next) = > {
    // ...
  });
Copy the code

4. Parameter transfer mode in router

(1) Address query

Routing: / users

Address: localhost: 4000 / users? q=1

Values: CTX. Query

Results: {q: 1}

(2) Obtain router Params

Routing: / users / : id

Address: localhost: 4000 / users / 1

Value: ctx.params

Result: {id: 1}

(3) Request body

Routing: / users

Localhost :4000/users, content-type: application/json, parameter {“name”: “zj”}

Value: KoA-bodyParser installed in advance: const bodyParser = require(” koA-bodyParser “); app.use(bodyParser()); Again: CTX. Request. The body

{“name”: “zj”}

5. Separate the API router to a separate file

The entry code imports the detached logic code, and the upper code imports the lower code

// demo/api/api1.js

const Router = require("koa-router");

const router = new Router();

router.get("/api1".async (ctx, next) => {
  ctx.body = "api1";
});

module.exports = router;

Copy the code
// demo/app.js

const Koa = require("koa");
const api1 = require("./api/api1");
const api2 = require("./api/api2");

const app = new Koa();
const port = 3000;

app.use(api1.routes()).use(api1.allowedMethods());
app.use(api2.routes()).use(api2.allowedMethods());

app.listen(3000);
console.log("The program has been started." + port + "Port listening");

Copy the code

Router.prefix () extracts the public parts of the path first

const router = require('koa-router')()

router.prefix('/users')

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 = router
Copy the code

RequireDirectory implements automatic route loading

Ideas:

1. Automatically look for the API file require in the folder

2. After router require is entered, it will automatically register with the app

Implementation: requireDirectory www.npmjs.com/package/req…

Simple usage:

const Koa = require("koa");
const Router = require("koa-router");

//requireDirectory is a direct export method
const requireDirectory = require("require-directory");
// the requireDirectory method returns an object with all routes
const routers = requireDirectory(module."./api");

const app = new Koa();
const port = 3000;

// Register each router with AppShang by convenience
for (let routerName in routers) {
  if (routers[routerName] instanceof Router)
    app.use(routers[routerName].routes()).use(routers[routerName].allowedMethods());
}

app.listen(port);
console.log("The program has been started." + port + "Port listening");
Copy the code

Advanced usage

const Koa = require("koa");
const Router = require("koa-router");
const app = new Koa();
const port = 3000;

function whenLoadModule(router) {
  if (router instanceof Router)
    app.use(router.routes()).use(router.allowedMethods());
}

//requireDirectory is a direct export method
const requireDirectory = require("require-directory");
The requireDirectory method also supports the opitons parameter, which configures the response callback function
requireDirectory(module."./api", { visit: whenLoadModule });

app.listen(port);
console.log("The program has been started." + port + "Port listening");
Copy the code

Complain less, think more. If you keep working hard, you will reap results.