Introduction to koaweb framework

Introduction to koa

koa -- Based on node Next generation web development framework based on JS platform

Koa is built by express staff and is committed to becoming a smaller and more expressive web framework. Using koa to write web applications can avoid repeated callback function nesting and improve the efficiency of error handling. Koa does not bind Middleware in the kernel. Similar to express, the biggest feature is that asynchronous nesting can be avoided.

koa installation and use

npm install --save koa

Project construction:

1. npm init --yes generate package json
2. Install koa npm install --save koa

**

Using koa router Middleware

**
npm install koa-router --save

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

const app = new Koa();
const router = new Router();

router.get('/', async (ctx) => {
  let html = `
      <ul>
        <li><a href="/hello">helloworld</a></li>
        <li><a href="/about">about</a></li>
      </ul>
    `
  ctx.body = html
}).get('/hello', async (ctx) => {
  ctx.body = 'How do you do'
}).get('/about', async (ctx) => {
  ctx.body = 'Guess what'
})

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

app.listen(3000);

middleware

Middleware Koa application is an object containing a set of middleware functions, which is organized and executed in a stack like manner. Use app in Koa Use () is used to load middleware. Basically, all functions of Koa are realized through middleware. Each middleware accepts two parameters by default. The first parameter is the Context object and the second parameter is the next function. As long as the next function is called, the execution right can be transferred to the next middleware.

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

// x-response-time
//Match all routes
app.use(async (ctx, next) => {			//A middleware
  const start = Date.now();
  await next();					//Wait asynchronously, match and process the next middleware
  const ms = Date.now() - start;		//Continue to return to execution after the matching reason is completed
  ctx.set('X-Response-Time', `${ms}ms`);
});

// logger

app.use(async (ctx, next) => {		//middleware 
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});

// response

router.get('news',asynx(ctx)=>{		//Match route news
	console.log("Matching route news")
})
app.listen(3000);

template engine

Render html pages.

Common rendering instructions:
1. Introducing public templates
<% include header.ejs %>

2. Binding data
<%= list %>

3. Bind html and parse dom elements
<%- value %>

4. Sharing data
ctx.state = {
commonTitle: 'I'm public data“
}

Install koa template using middleware

$ npm i --save koa-views

Install ejs template engine

$ npm i --save ejs

const Koa = require('koa')
const views = require('koa-views')
const path = require('path')
const app = new Koa()

// Load template engine
app.use(views((__dirname, './view'), {		//For example, the dirname here is index
    extension: 'ejs'
}))
app.use(async(ctx)=>{
	ctx.state.commonTitle = "Title of public reuse";
	await next();			//Continue to match down
})
app.use(async (ctx) => {
    let title = 'Koa2'								//Single data
    let list = ['111','222']
    await ctx.render('index', {			//In index Rendering title data in EJS
        title,										
        
    })
})

app.listen(3000)

./view/index.ejs template

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <h1><%= title %></h1>				//Render title
    <h2><%=commonTitle %></h2>  //Render public resources  
    <div>
    	<%    for(var i = 0;i<list.length;i++) {    %>
				<p><%=list[i]  %></p>			//Render list array
	}
    </div>
</body>
</html>

Static resource Middleware

1,cnpm install koa-static --save

2,const static = require('koa-static')

3. Configure app Use (static ('public ') / / public is the directory name of static resources
Configuration can also be written to app use(static (__dirname + ‘/public’))

Template engine art template
koa cookie
Cookies are stored in the browser client, saving information, browsing history, remembering passwords, etc
Insert picture description here
ctx.cookies.set('userlist','zhangsan',{
maxAge:60 * 1000 * 60,
path: '/ news', / / configurable pages
domain:‘baidu.com '/ / no configuration under normal conditions
})

ctx.cookies.get('userlist')

session

Session is another mechanism to record the status of customers. The difference is that the session is saved in the server.

When the browser accesses the server for the first time, the server will create a session object, generate a similar key value pair of key and value, and then return the key to the browser. When the browser accesses again, it will carry the key(cookie) and find the corresponding value.

//Middleware for configuring seesion

app.keys = [’ some secret hurr’]; // Signature of cookie

```javascript
const CONFIG = {
key: 'koa:sess',
maxAge:300,
overwrite:true,
httpOnly:true,
signed:true,
rolling:false,
renew:true
}

app.use(session (CONFIG,app));
//Get session

ctx.session.userinfo = 'Zhang San';

operation mongodb database
1,install mongodb

cnpm install mongodb --save

2,introduce mongodb Below mongoClient

var MongoClient = require('mongodb').MongoClient;

3,Define the address of the database link and configure the database

var url = 'mongodb 😕/localhost:8080/koa'

4,node.js Connect database
MongoClient.connent(url,(err,client)=>{
const db = client.db(dbName) ; database db object

})

5,Operation database
db.user.insert
MongoClient.connect(url,(err,db)=>{
db.collection('user').insertOne({"name":""Zhang San"},(err,result) =>{
db.close();
})
})

## sequelize

sequelize(Sequelize Is based on promise of nodejs orm,Current support Postgres,mysql,SQLite and Microsoft SQL Server. It has powerful transaction support, association, read and copy functions.)

Tags: node.js Middleware koa

Posted by sunsun on Sat, 16 Apr 2022 13:50:11 +0930