nodejs server development refers to the use of koa2

1, koa and express

  • 1. They are all the framework of node web development
  • 2. There are two versions of koa, one is 1. * written by Generator, and the other is written by async
  • 3. koa's official website is relatively simple Portal

2, Start using koa

  • 1. It is also introduced on the kao official website that you can use async only when the node version is greater than 7.6, otherwise you need to configure plug-ins
  • 2. Run a hello word using the official case

    const Koa = require("koa");
    const app = new Koa();
    app.use(async (ctx) => {
      ctx.body = 'Hello World';
    })
    
    app.listen(3000, () => {
      console.log(`Server started:localhost:3000`);
    });

3, The reason why the koa official website is so simple is that it's completely different from the previous express. It's used to separate our common routes, static files, etc

4, Use routing

  • 1. Installation package

    npm install koa-router --save
  • 2. Use

    **router file**
    const Router = require('koa-router');
    const router = new Router();
    
    router.get('/', async (ctx) => {
      ctx.body = `<h1>Hello</h1>`;
    })
    
    module.exports = router.routes();
    
  • 3. Use in main file

    app.use(require('./routers/user'));
  • 4. Configure child routes

    const Router = require("koa-router");
    const router = new Router();
    
    router
      .get("/", async ctx => {
        ctx.body = `
          <ul>
            <li><a href="/hello">helloworld</a></li>
            <li><a href="/about">about</a></li>
          </ul>
        `;
      })
      .get("/hello", async ctx => {
        ctx.body = "helloworld";
      })
      .get("/about", async ctx => {
        ctx.body = "about";
      });
    
    module.exports = router.routes();

5, Using static files

  • 1. Installation package

    npm install koa-static --save
  • 2. Use

    **In main file**
    const static = require('koa-static');
    const path = require('path');
    // Static storage address
    const staticPath = './static';
    
    app.use(static(
      path.join(__dirname, staticPath)
    ))
    

6, get request data acquisition

  • 1. get requests send json to the front end

    const Router = require("koa-router");
    const router = new Router();
    
    router.get("/query", async ctx => {
      // Get url 
      const url = ctx.url;
      // Get client parameters
      const query = ctx.query;
      // Get all parameters after
      const querystring = ctx.querystring;
      ctx.body = {
        url,
        query,
        querystring
      };
    });
    
    module.exports = router.routes();

7, post submit data

  • Installation package

    npm install koa-bodyparser --save
  • 2. Main file configuration KOA bodyparser Middleware

    **In main file**
    const bodyParser = require('koa-bodyparser');
    // Using koa body parser Middleware
    app.use(bodyParser());
  • 3. Configure routing

    router.post("/create", async ctx => {
      console.log(ctx.request.body);
      ctx.body = {
        name: ctx.request.body.name
      };
    });

8, koa configuration cross domain access

  • 1. Configure Middleware in the main file

    npm install --save koa2-cors
    var koa = require('koa');
    var cors = require('koa2-cors');
    
    var app = koa();
    app.use(cors({
      origin: function(ctx) {
        if (ctx.url === '/test') {
          return false;
        }
        return '*';
      },
      exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
      maxAge: 5,
      credentials: true,
      allowMethods: ['GET', 'POST', 'DELETE'],
      allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
    }));

9, Use ejs template engine (it's popular to develop the front and back end separately now, so it's not used very much)

  • 1. Install the koa views view package

    npm install koa-views --save
  • 2. Install ejs simulation engine

    npm install ejs --save
  • 3. Template engine used for configuration in master file

    const path = require('path')
    const views = require('koa-views');
    // Load template engine
    app.use(views(path.join(__dirname, './view'), {
      extension: 'ejs'
    }))
    
    // Render template
    app.use(async ctx => {
      let title = "Koa2";
      // Rendering template and return parameters
      await ctx.render("index", {
        title
      });
    });

Welcome to group chat, let's discuss the front-end technology stack

Group No.: 560285778

Tags: npm Web Development JSON

Posted on Sun, 03 May 2020 20:39:25 -0400 by prion