This article has participated in the good article call order activity, click to see: back end, big front end double track submission, 20,000 yuan prize pool for you to challenge!

Koa address: koa.bootcss.com/#introducti…

Koa is introduced

Koa is a new Web framework built by the same people behind Express that aims to be a smaller, more expressive, and more robust building block for web application and API development. By using async functions, Koa helps you discard callbacks and greatly enhances error handling. Koa doesn’t bundle any middleware, but rather provides an elegant way to write server-side applications quickly and happily.

Open the service

Koa is very simple to use, with the following steps

  1. Initialization file
  2. Installation of koa
  3. The introduction of koa
  4. Create an instance and run the instance again, listening on port 3000.

The following code

Initialization file

npm init -y

Copy the code

The tsconfig.json configuration is as follows

{
  "compilerOptions": {
    "module": "commonjs"."target": "esnext"."outDir": "./dist"."experimentalDecorators": true."emitDecoratorMetadata": true."resolveJsonModule": true."typeRoots": []}}Copy the code

Installation of koa

npm install koa @types/koa typescript
Copy the code

Introduce and start the service

Create the index.ts file

import * as Koa from "koa"
const app = new Koa()

app.use(async (ctx, next) => {
  ctx.body = 'hello world'
})

app.listen(3000)
Copy the code

Start ts listening

tsc -w
Copy the code

Run the supervisor command at the same time

supervisor ./dist/index.js
Copy the code

Go to http://localhost:3000/

Successful run!!

Static Resource Management

Creating a folder

Create static static folders to store images, scripts, and CSS files

Install the dependency and use it

Installation of koa – static – cache

npm install koa-static-cache
Copy the code

Introduce koA-static-cache and use it

app.use(KoaStaticCache('./static', {gzip: true.prefix:'/public'.dynamic: true,}))Copy the code
  1. Prefix: indicates the URL prefix to be added
  2. Gzip: When the requested acceptance encoding contains GZIP, the file is gZIP compressed.
  3. Dynamic: whether to cache assets at initialization. The default istrue

Template to use

Select nunjucks, the official website address: nunjucks.bootcss.com/

Method of use

npm i nunjucks
Copy the code

File and use

app.use(async (ctx,next)=>{
  ctx.template = new Nunjucks.Environment(
    new Nunjucks.FileSystemLoader(process.cwd()+'/views/'), {autoescape: false});await next();
})
Copy the code

Installation and use of controller

The installation

npm i koa-controllers
Copy the code

use

useControllers(
  app,
  __dirname + "/controllers/**/*.js",
  {
    multipart: {dest: process.cwd() + '/static/uploads/avatar',}})Copy the code

To access the page

Now that we’ve done all the preparatory work, we’re ready to create our first interface and access our page.

Creating an interface File

import {Controller,Get,Ctx, Post } from 'koa-controllers';
import { Context } from 'koa';

@Controller
export class MianIndexController {

  @Get('/')
  public async index(@Ctx ctx:Context) {
    ctx.body = ctx.template.render('index.html')}}Copy the code

Reaccess the previous path

Apply colours to a drawing template

Ctx.template-render can also be followed with data used to render templates for example

  @Get('/')
  public async index(@Ctx ctx:Context) {
    const list = [
      {id: 0.name: 'I am koA's first template data'},
      {id: 1.name: 'I am koA's second template data'},
      {id: 2.name: 'I am koA's third template data'},
    ]
    ctx.body = ctx.template.render('index.html', { list: list, name: 'koa case' });
  }
Copy the code

The syntax for template rendering can be directly referred to the documentation. For syntax is as follows

<h1>{{name}}</h1>
  <ul>
  {% for item in list %}
    <li>{{ item.name }}</li>
  {% endfor %}
</ul>
Copy the code

The effect is as follows:

The proxy service

Installation and use of agents

Installation of koa – server – HTTP proxy

npm i koa-server-http-proxy
Copy the code

The use method is as follows:

const proxyTable = {
  '/dev': {target:'http://xxxx.com'.pathRewrite: { '^/dev': ' ' },
    changeOrigin: true}}Object.keys(proxyTable).forEach((context) = >{
  var options = proxyTable[context]
  app.use(proxy(context,options))
})
Copy the code

Use of pages

<script src="./public/js/jquery.min.js"></script>
<script>
(function(){
  let data = 'parameters'
  let url = 'dev/url'
  $('.btn').on('click'.function(){
    $.ajax({
      method: 'POST'.url:'dev/url'.contentType: 'application/json'.data: JSON.stringify(data)
    }).done(data= >{
      console.log(data)
    })
  })
})()
</script>
Copy the code

conclusion

Before learning this KOA is to do the site server rendering, there is also the idea of learning backend language, but in the end there is no use this way. Let me write this down for you to remember later.

Have wrong place, also please much guidance, welcome point like, leave a message!!

Related articles

Flex Layout Summary:Juejin. Cn/post / 698497…

Mongodb basic usage:Juejin. Cn/post / 698364…

Regular expression summary:Juejin. Cn/post / 698615…