Koa – initial experience (write an interface)

Time:2019-12-12

Preface

  Can’tnode.jsThe front end of is not a good front end!

These yearsnode.jsIt’s getting hotter and hotter. Many companies are rightnode.jsAll began to ask. Although the front end doesn’t have to know the back end, it wants to be an excellent front end,node.jsIs the only way.

I’m interested innode.jsThe first impression is that it is a back-end language, but the front-end learning cost will be lower and better. After slowly understanding, usenode.jsWrite interface is very convenient for front-end, but not limited to write interface. In some big companies,node.jsIt’s not the preferred goal of developing interfaces, but as a middle tier. We all know that division of labor and cooperation, so that professional people do more professional things, work efficiency will be greatly improved.node.jsAs an intermediate layer, the back end can be more focused on writing interfaces and managing data.

Just think, now that the business logic changes and the backend needs to change the data interface, will it take time? If you willnode.js, then you can passnode.jsTo do data aggregation, splicing data from several interfaces for front-end use, without worrying about data structure and data content, and you don’t need to worry about efficiency, becauseNode.js is inherently asynchronous.

  Some of our common scaffolding tools are also based onnode.jsEnvironment building, you can even usenode.jsTo do data mining, which is what we call crawler,node.jsThere are many application levels of. These are some of the information I have learned.

at presentnode.jsThe main frameworks are express, KOA and egg.As a new generation framework, KOA is built by the original team who developed express. It supports ES7 async / await, discards callback functions, and is more natural in writing.Koa does not bind anyPieces,The key design point is to provide high-level “grammar sugar” in its low-level middleware layer, so the size of KOA is smaller.(middleware is a very important existence in koa, I will focus on learning it later.)

Next, I’m going to start the path of KOA into the pit.

 

Koa first experience

hello,koa!

Installation of KOA, NPM I KOA

Create an app.js and execute it on the command linenode app

const Koa = require('koa' );
const app = new Koa();

app.context.msg = 'Hello Koa!' 
app.use(async ctx => {
  ctx.body = ctx.msg;
});

app.listen( 3000);

app.context Add properties and methods for execution context

app.use Add the given middleware method to the application

This method receivesctxandnextAs a parameter,ctx It is the execution context, which stores information such as request and response, as well as ctx.body, through which we can return data. Next is a function call, and the execution right is handed to the next middleware for execution.

Here I install a nodemon first, because every time I change a file, I need to re execute the command to update the code, and this repetitive work is left to the module to handle.

adoptnpm i nodemonAfter installation, the command line executesnodemon app, so that nodemon will refresh automatically every time the file is changed.

 

Koa router route management

In order to maintain the code and reduce the amount of code.It is very important to use routing management. Koa framework also has its own routing management module (KOA router). We can download and use it through NPM.

var Koa = require('koa' );
var Router = require('koa-router' );
 
var app = new Koa();
var router = new Router();
 
router.get( '/', (ctx, next) => {
      ctx.body = 'hello'
});
//Using routing Middleware
app
  .use(router.routes())
  .use(router.allowedMethods());

app.listen( 3000 )

Routes register to use routes

allowedMethods The business to be handled is that after all routing middleware are executed, if ctx.statusWhen it is empty or 404, rich responseObject’s headerHead, it’s not a big problem if it’s not added. The official example is added, so I’ve added it here

At this time, you can access port 3000 to get the content returned by ctx.body

Get request

1. Get interface query parameters

The get parameters are obtained by querying ctx.request.query, the header information is obtained by ctx.request.header, and the request method is obtained by ctx.request.method. In this way, we can make some corresponding judgments, such as whether the parameters of the request are legal or not, and whether the request method is legal.

router.get( '/get', (ctx, next) => {
      let id = ctx.request.query.id
      ctx.body = {
           id,
           code: 1
      }
});

 

2. Named route get parameters

router.get( '/get/:id', (ctx, next) => {
      let id = ctx.request.params.id
      ctx.body = {
           id,
           code: 1
      }
});

For example, if the request address is / get / 123, get the parameters through ctx.request.params

This method reminds me of Vue router. Setting params is the same.

 

Post request

To obtain the parameters of the post request, you need to listen to the data event and end event of ctx.req, segment and splice them into a complete string, and then you need to cut and transcode. So when I get the post parameter, I will use the koa body parser to reduce unnecessary operations.

When introducing the KOA bodyparser, we need to pay attention to the order problem. When using the KOA bodyparser, we need to put it before using the route. This is because of the execution order of the middleware (for now, it is understood that the bodyparser has been processed and the processed values are transferred to the route)

var bodyParser = require('koa-bodyparser');

app.use(bodyParser());

app
    .use(passport.initialize())
    .use(passport.session())

 

With the help of middleware KOA bodyparser, visit ctx.request.body to get the post parameter

Set the return header through ctx.set, and pass in objects when setting multiple

Route. Post ('/ post', CTX = > {// set to allow cross domain CTX. Set ('Access control allow origin '*')
    ctx.body = {
        code:1,
        postParams:ctx.request.body
    }
})

 

Route modular management

Imagine that there are multiple interfaces written in the file now. We will be particularly troublesome and waste time in development and debugging. In order to better manage the interface, we need to extract the interface according to the function, package it into JS files one by one, and store it in the routes folder.

For example, create user.js to store user related interfaces

const Router = require('koa-router')
const route = new Router()
const jwt = require('jsonwebtoken')

route.get('/getToken', async (ctx)=>{
    let {name,id} = ctx.query
    if(!name && !id){
        ctx.body = {
            MSG: 'illegal',
            code:0
        }
        return
    }
    //Generate token
    let token = jwt.sign({name,id},'secret',{ expiresIn: '1h' })
    ctx.body = {
        token: token,
        code:1
    }
})

route.get('/getUser', async ctx=>{
    let id = ctx.query.id
    ctx.body = {
        user:ctx.payload,
        id,
        code:1
    }
})

route.get('/getAllUser', async ctx=>{
    let type = ctx.query.type
    if(type){
        ctx.body = {
            type,
            code:1
        }
    }else{
        ctx.body = {
            MSG: 'missing parameter type',
            code:0
        }
    }
})

module.exports = route

The above code exposes the written interface for app.js registration

 

App.js code (some codes are omitted)

let urls = fs.readdirSync(__dirname + '/routes')
urls.forEach((element) => {
    //JS interface file in routes
    let module = require(__dirname + '/routes/' + element)
    //File name in routes as route name
    router.use('/' + element.replace('.js', ''), module.routes())
})

//Use routing
app.use(router.routes()).use(router.allowedMethods())

app.listen(3000)

Above code, I will talk about the process

1. FS file module reads the contents of routes folder directory (obtaining an array of file names)

2. Array traversal, import interface file, take file name as route name, register and use route

Take user.js as an example. There is a getuser interface in user.js. The API address I access is / user / getuser

 

Head information processing

In the front-end and back-end interaction, header information is also a key step. Through the configuration of header information, you can make some restrictions on the request, or some optimization.

Here I will use koa2 CORS as an example to do cross domain CORS processing (some code is omitted).

const cors = require('koa2-cors')

app.use(cors({
    origin: function(ctx) {
      return 'http://127.0.0.1:5500';//cors
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

app.use(router.routes()).use(router.allowedMethods())

app.listen(3000)

origin: accept strings and functions. The configuration here is to allow cross domain domain domain names. If all domain names are allowed to cross domain, they can be passed in*

allowMethods: how requests are allowed

allowHeaders: allowed header information

Other configuration options can be viewed on NPM: https://www.npmjs.com/package/koa2-cors

 

Written in the end

In this paper, the interface is realized simply by routing middleware, the interface file is managed by modularity, and the interface is processed across domains.

The main thing is to play the module, through which you can combine the system suitable for your business.