1 Project Construction

1.1 Initializing a Directory

Install mkdir koa-demo && CD koa-demo && NPM init -y && NPM I koa –save && code.

Configure in package.json file:

"scripts": {
  "test": "echo \"Error: no test specified\" && exit 1",
  "start": "node index.js"
}
Copy the code

1.2 Creating a Root Directoryindex.jsfile

Const Koa = require(' Koa ') const app = new Koa() // Middleware app.use((CTX) => { Res) = > {res. The end (' hello, uncertainty ')}) CTX. Body = 'hello, uncertainty}) app. Listen (3000, () = > {the console. The log (' listen on port 3000)})Copy the code

Body = ‘

Hello, I’m not sure

‘, so the page can render the tag directly; But now the projects are separated from the front and back ends. The back end directly returns JSON data, and the front end is rendered after it is taken, so the data Koa returns is like this: CTx. body = [{name: ‘uncertainty’}, {name: ‘uncertainty’}].

Perform NPM start

Open your browser and type http://localhost:3000/

Of course, you can use your browser to view it now because it is a GET request, but I recommend you to install Postman so that you can easily test post requests or upload files later. Postman download address.

1.3 the use ofpostmanrequesthttp://localhost:3000/

However, every time the code is changed, the service needs to be restarted, which is not very convenient. Here, we install the Nodemon auxiliary tool, and it will be refreshed automatically after the change. It can be installed globally or under the current project, and I will install NPM I nodemon-g globally.

Example Change the startup command to"start": "nodemon index.js"nodemonWill help us listen injs, mjs, jsonFile changes, automatically start the program)

2 Simple implementationKoa

As we all know, Koa is the encapsulation of Node, starting with a simple service implementation:

  • The new fileapplication.js

Koa is an instance of new, so we need to implement a class, listen method to listen port, use method to mount middleware, as follows:

Constructor () {this.callbackfunc} //... args) { let server = http.createServer(this.callback()) server.listen(... Args)} @param {*} fn callback handler */ use(fn) {this.callbackFunc = fn} /** * Get the HTTP server callback function */ callback() { return (req, res) => { this.callbackFunc(req, res) } } } module.exports = ApplicationCopy the code
  • newexample.jsfile

Import the application.js file you just created

let simpleKoa = require('./application') let app = new simpleKoa() app.use((req, Res) => {res.writehead (200) res.end(' Uncertainty ')}) () => console.log(' Listen on port 8000 ')Copy the code
  • Execute the commandnodemon example.js

3 the middleware

Koa is a middleware framework that does not bundle any middleware itself (the core code is concise). It does not support many functions, functions can be achieved through middleware expansion. Build a Koa application by adding different middleware to fulfill different requirements. Koa’s middleware is a function, which is now mostly async functions.

  • App.use () is used to register middleware and must be a generator function.
use(fn) { if (typeof fn ! == 'function') throw new TypeError('middleware must be a function! '); if (isGeneratorFunction(fn)) { deprecate('Support for generators will be removed in v3. ' + 'See the documentation for examples of how to convert old middleware ' + 'https://github.com/koajs/koa/blob/master/docs/migration.md'); fn = convert(fn); } debug('use %s', fn._name || fn.name || '-'); this.middleware.push(fn); return this; }Copy the code

Generator functions: Generator generator is a special function added to ES6. It is declared by function*, and the function body uses yield to indicate the pause point of the function. The function returns an iterator, and the function is paused until the yield statement. The yield statement is then executed by calling the returned iterator next() method

We can also use generator functions for middleware (not recommended) :

const Koa = require('koa') const app = new Koa() app.use(function *(next){ console.log(1) yield next; Console. log(3) this.body = 'Hello, Use (function *(next){console.log(2) yield next}) app.listen(3000, () => {console.log(' console.log ')})Copy the code

  • Koa’s middleware cascades in a more traditional way, eliminating the complex code logic of node’s frequent callbacks

  • Koa puts many middle key functions into a processing chain, each of which can do its own thing, and then calls the next middle key function with next()

  • The intermediate key must be a function that can be asynchronous: handled with async and await in ES7

  • Use internally encapsulates two objects: CTX and next

  1. ctxcontextCommonly known as context, mainly includesrequestresponse.bodyhttpThe response body in the protocol,headerThe response header can be used directly if you want to throw an exceptionCtx. throw(500, 'interface exception ').ctx.statusSet the status code,ctx.urlGet requestURLAnd so on.
  2. nextAct as tandem middleware through callsnextFunction to hand execution to the next middleware. The last middleware does not use this function.

4. Write your own middleware

4.1 logThe middleware

The log module is also an indispensable part of the line, and the perfect log system can help us quickly troubleshoot the problems on the line. With Koa middleware, we can implement our own logging module (directly from the community’s off-the-shelf libraries, of course):

  • newlogger.js
const fs = require('fs') module.exports = (options) => async (ctx, next) => { const startTime = Date.now() const requestTime = new Date() await next() const ms = Date.now() - startTime Let the logout = ` ${CTX. Request. IP}, ${requestTime} - ${CTX. Method} - ${CTX. Url} - ${} ms ms ` / / output log file fs.appendFileSync('./log.txt', logout + '\n') }Copy the code
  • Import file importlogger.jsfile
const Koa = require('Koa')
const app = new Koa()
const logger = require('./logger')

app.use(logger())

app.listen(3000, () => {
    console.log(`Server port is 3000.`)
})
Copy the code

4.2 tokenvalidation

In the separate development of the front and back ends, JWT is often used for authentication, in which token is generally placed in the Header Authorization field of HTTP request (to be introduced later). Each request requires verification at the back end, and it is impossible to write judgment for each interface. Koa implements token verification by writing middleware.

  • createtoken.js
module.exports = (options) => async (ctx, Next) {try {// Obtain token const token = ctx.header.authorization if (token) {try {// verify function verify token, Await verify(token)} catch (err) {console.log(err)}} // enter the next middleware await next()} catch (err) { console.log(err) } }Copy the code
  • Import file importtoken.jsfile
const Koa = require('Koa')
const app = new Koa()
const token = require('./token')

app.use(token())

app.listen(3000, () => {
    console.log(`Server port is 3000.`)
})
Copy the code

Like friends can pay attention to the public number: with the front end, learning and progress together in 2021.