preface
Koa is the next generation Web development framework based on node.js platform. It is small in size, strong in scalability, and gives people a clean programming method. It is built by the original team of Express, and many Domestic Internet companies are using it.
Fresh out of school, say hello word
- As usual, I’m going to do a demo and say Hello World
let Koa = require('koa'); / / the introduction of koaletapp = new Koa(); // Declare an instance app app.use(async (CTX,next)=>{// For any request, app will call this asynchronous function to process the request: ctx.body ="hello"
});
app.listen("3000"); // Listen on the portCopy the code
- The parameter CTX is a variable passed in by KOA that encapsulates request and Response. We can access request and Response through it.
- Next is the next asynchronous function koA passes in to process.
- A function marked with async is called an asynchronous function. In an asynchronous function, we can call another asynchronous function with await. The asynchronous function must return a promise. These two keywords will be introduced in ES7.
Five lines of code helped us turn on port 3000
In-depth understanding of Koa middleware onion model
The focus of learning Koa is to understand the implementation principle of middleware and have a better understanding of the subsequent reference to third-party library middleware. Let’s talk about it separately
- Let’s start with some test code
let Koa = require('koa');
let app = new Koa();
app.use(async (ctx,next)=>{
console.log(1);
await next();
console.log(2);
});
app.use(async (ctx,next)=>{
console.log(3);
await next();
console.log(4);
});
app.listen("3000");
Copy the code
You might say 1234 for the result of the run, but it’s not. Let’s look at the output
What order is that? That’s the onion model we’re talking about
- Middleware execution is like an onion, but rather than layer by layer, it is bounded by next, executing the parts of the layer before Next, and executing the parts of the layer after Next when the next layer is finished.
- An onion structure, from the top down a layer in, and then from the bottom up a layer back, is not a little feeling.
1. Koa-router middleware
Koa-router is written in basic form
- In order to explain the detailed and comprehensive, the route is divided into parts to explain, first look at the most basic route how to write
let Koa = require('koa');
let app = new Koa();
let Router = require('koa-router');
let router = new Router();
router.get('/',async (ctx,next)=>{
ctx.body = 'hello people';
await next()
});
router.get('/list',async (ctx,next)=>{
ctx.body = 'list'; }); app.use(router.routes()); / / mount app. Use (the router. The allowedMethods ()); // An error is reported when the requested data method is inconsistent with the set method. App.listen (3000); app.listen(3000);Copy the code
Koa-router nested routines are written as follows
If we want to hierarchy individual pages, /home is our home page, and then again, based on that, we have /home/list home page list page /home/todo home page todo page. Then we need to use nested routines, see how to use
const Koa = require('koa');
const app = new Koa();
const Router = require('koa-router'); / / home routinglet home = new Router();
home.get('/list',async(ctx)=>{
ctx.body="Home list";
}).get('/todo',async(ctx)=>{
ctx.body ='Home ToDo'; }); / / page routinglet page = new Router();
page.get('/list',async(ctx)=>{
ctx.body="Page list";
}).get('/todo',async(ctx)=>{
ctx.body ='Page todo'; }); // Load all child routeslet router = new Router();
router.use('/home',home.routes(),home.allowedMethods());
router.use('/page',page.routes(),page.allowedMethods()); App.use (router.routes()).use(router.allowedMethods()); app.listen(3000);Copy the code
In this way, the writing method of nested routines will be realized
Pass of koA-router parameters
- Pass parameters through /arcicle/id/name
let Koa = require('koa');
let app = new Koa();
let Router = require('koa-router');
letrouter = new Router(); // implement /arcicle/id/name router.get()'/acticle/:id/:name',(ctx,next)=>{
ctx.body = ctx.params.id +"-"+ ctx.params.name;
});
app.use(router.routes());
app.listen(3000);
Copy the code
For the test, you should be familiar with VUE
- 2, through /arcicle? Id = 1 & name = CGP refs
const Koa = require('koa');
const Router = require('koa-router');
const app = new Koa();
const router = new Router();
router.get('/article'.function(ctx, next) { ctx.body=ctx.query; }); app.use(router.routes()) app.listen(3000,()=>{ console.log('starting at port 3000');
});
Copy the code
2. Koa – BodyParse () Middleware
- The middleware used to parse the request body, such as retrieving form data submitted by POST, is parsed through KOA-BodyParse to retrieve the data. Look at the demo
let Koa = require('koa');
let bodyParser = require('koa-bod')
letapp = new Koa(); app.use(bodyParser()); Use (async (CTX, next) => {if (ctx.path === '/' && ctx.method === 'GET') {
ctx.set('Content-Type'.'text/html; charset=utf8');
ctx.body = `
<form action="/" method="post">
<input type="text" name="username" >
<input type="text" name="password" >
<input type="submit" >
</form>
`
}
});
app.use(async (ctx, next) => {
if (ctx.method === 'POST' && ctx.path === '/'Ctx.body = ctx.request.body; }}); app.listen(3000);Copy the code
When the post submits the form and gets the form data, test the results
3. Koa-better-body middleware
- Middleware for uploading files
- Since the older middleware was implemented based on the koA1 version of generate, in KOA2 we needed koA-convert, which can be converted to Promise based middleware for KOA2 to use
For a demo, upload the local 1.txt file to the upload folder. 1. The content of the TXT file is 123456789
let Koa = require('koa');
let app = new Koa();
let betterBody = require('koa-better-body'); / / v1 plug-inlet convert = require('koa-convert'); Use (convert(betterBody({uploadDir: __dirname // Specify directory to upload __dirname Absolute path of current folder}))) app.use(async (CTX, next) => {if (ctx.path === '/' && ctx.method === 'GET') {
ctx.set('Content-Type'.'text/html; charset=utf8');
ctx.body = `
<form action="/" method="post" enctype="multipart/form-data">
<input type="text" name="username" autoComplete="off">
<input type="text" name="password" autoComplete="off">
<input type="file" name="avatar">
<input type="submit" >
</form>
`
} else {
returnnext(); }}); app.use(async (ctx, next) => {if (ctx.method === 'POST' && ctx.path === '/'Body = ctx.request.fields; }}); app.listen(1000);Copy the code
Take a look at the upload results
And the content is correct, so I’m not going to show you
4. Kao-views middleware
- Koa-views is an indispensable middleware for applications that require view template rendering, supporting ejS, Nunjucks and many other template engines.
Let’s take ejS as an example
let Koa = require('koa');
let app = new Koa();
let views = require('koa-views');
app.use(views(__dirname,{
extension:'ejs'})); App. use(async (CTX,next)=>{// render index.ejs await ctx.render('index',{name:'cgp', the age: 9, arr: [1, 2, 3]}); }); app.listen(3000);Copy the code
- Let’s look at how the index.ejS template is written. Ejs syntax stamp here
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1><%=name%></h1>
<h1><%=age%></h1>
<ul>
<%arr.forEach(item=>{%>
<li><%=item%></li>
<%})%>
</ul>
</body>
</html>
Copy the code
- The template we wrote here is very simple, just print name, age, and loop through the array
5, koa – static
- A middleware for generating static services The previous article wrote a module for CPG-Server
let Koa = require('koa');
let server = require('koa-static');
let app = new Koa();
app.use(server(__dirname +'/public'));
app.listen(3000);
Copy the code
- The usage is very simple, interested can look at the static server I wrote
6, KOA built-in cookie usage
For example, when we want to store the user name and keep the user logged in, we use cookies.
There are two methods
- ctx.cookies.get()
- ctx.cookies.set()
Let’s do a demo test. When you type /write, you write cookies, and when you type /read, you read cookies
let Koa = require('koa');
let Router = require('koa-router');
let app = new Koa();
let router = new Router();
router.get('/read', (CTX, next) => {// there is a name read namelet name = ctx.cookies.get("name") | |'no name';
let age = ctx.cookies.get("age") | |'there is no age';
ctx.body = `${name}-${age}`;
});
router.get('/write', (ctx, next) => {
ctx.cookies.set('name'.'cgp',{
domain:'127.0.0.1'// Write the domain name path where the cookie is located:'/write', // maxAge:10*1000, // cookie Max duration httpOnly:false// Whether to get overwrite only in HTTP requests:false}); ctx.cookies.set('age'.'9');
ctx.body = 'write Ok';
});
app.use(router.routes());
app.listen(4000);
Copy the code
Cookie options
- Domain: indicates the domain name of the cookie
- Path: indicates the path where the cookie is written
- MaxAge: indicates the maximum validity period of cookies
- Expires: indicates the cookie expiration time
- HttpOnly: Whether to obtain only from HTTP requests
- Overwirte: Indicates whether overwriting is allowed
Let’s take a look at the results
To be continued
Interested in common middleware source code can refer to my summary
Read more of the original article here
You can see it here. Give it a thumbs up if you like