Home Web Front-end JS Tutorial Node uses Koa2 to build web projects

Node uses Koa2 to build web projects

Jan 15, 2018 pm 01:10 PM
koa2 node web

This article mainly introduces the method of node using Koa2 to build web projects. The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

As Node.js becomes increasingly popular, various frameworks begin to emerge one after another, and Node.js is gradually being applied to scenarios where server-side requests are processed. Frameworks for building Web projects also began to appear - express, koa, koa2, egg, etc. Of course, to understand their quality, you still have to read the source code yourself. This article will not involve the source code, but will only lead beginners to briefly understand the basic use of Koa2. Everyone is welcome to communicate and learn from each other in the comments.

Note: koa2 uses ES7 syntax, so please upgrade the Node version to the latest when using it. For more detailed source code information, you can go to koajs/koa on git to learn

1. Project directory structure

2. Code logic analysis

2.1. Package structure file

[package.json]


{
 "name": "weixin-node-koa",
 "version": "1.0.0",
 "description": "node.js with koa2",
 "private": true,
 "dependencies": {
  "koa": "^2.0.0",
  "koa-router": "^7.0.0",
  "mysql":"2.13.0"
 },
 "scripts": {
  "start": "node app.js"
 },
 "engines": {
  "node": ">=6.0.0"
 },
 "author": "Fly",
 "license": "CENTERM"
}
Copy after login

2.2. Start the entry file

[app.js]


##

const Koa = require('koa');
const app = new Koa();
const router2controller = require('./app/router2controller.js');
const config = require('./config/config.local.js');

app.use(router2controller());
app.listen(config.port);
console.log("Server started and listen on port " + config.port);
Copy after login

If the requested message body is In XML format, you can add the following code to automatically parse the message (note that the version quoted from koa-xxx must correspond to koa2)

##

const Koa = require('koa');
const app = new Koa();
const router2controller = require('./app/router2controller.js');
const config = require('./config/config.local.js');

//start接收到的xml数据请求单独解析存储
const xmlParser = require('koa-xml-body');
app.use(xmlParser()).use((ctx,next) => {
  ctx.data = ctx.request.body;
  return next();
});
//end

app.use(router2controller());
app.listen(config.port);
console.log("Server started and listen on port " + config.port);
Copy after login

From the code, we can see that a router2controller is introduced. js file, this file is the routing process that completes the front-end request to the specific processing method

2.3. Router file

[router2controller.js]

This class will automatically scan the files in the controller folder to load the request mapping. There is no need to configure each request separately.


koa-router natively provides the following methods:


router
 .get('/', async (ctx,next) => {
  this.body = 'Hello World!';
 })
 .post('/users', async (ctx,next) => {
  //TODO
 })
 .put('/users/:id', async (ctx,next) => {
  //TODO
 })
 .del('/users/:id', async (ctx,next) => {
  //TODO
 });
Copy after login

The implementation method of automatically scanning the controller package is as follows


const fs = require('fs');
const router = require('koa-router')();

function addMapping(router, mapping) {
  for (var url in mapping) {
    if (url.startsWith('GET ')) {
      var path = url.substring(4);
      router.get(path, mapping[url]);
      console.log(`register URL mapping: GET ${path}`);
    } else if (url.startsWith('POST ')) {
      var path = url.substring(5);
      router.post(path, mapping[url]);
      console.log(`register URL mapping: POST ${path}`);
    } else if (url.startsWith('PUT ')) {
      var path = url.substring(4);
      router.put(path, mapping[url]);
      console.log(`register URL mapping: PUT ${path}`);
    } else if (url.startsWith('DELETE ')) {
      var path = url.substring(7);
      router.del(path, mapping[url]);
      console.log(`register URL mapping: DELETE ${path}`);
    } else {
      console.log(`invalid URL: ${url}`);
    }
  }
}

function addControllers(router, dir) {
  fs.readdirSync(__dirname + '/' + dir).filter((f) => {
    return f.endsWith('.js');
  }).forEach((f) => {
    console.log(`process controller: ${f}...`);
    let mapping = require(__dirname + '/' + dir + '/' + f);
    addMapping(router, mapping);
  });
}

module.exports = function (dir) {
  var controllersDir = dir || 'controller';
  addControllers(router, controllersDir);
  return router.routes();
};
Copy after login

2.4. Controller

[userController.js]

***Controller.js is used to process specific request information and return data. userController.js handles GET requests to obtain user information, and POST requests to save user information


const userService = require('./../service/userService.js');

var getUserinfo = (ctx, next) => {
  let query = ctx.query;
  let userId = query.id;
  let userInfo = userService.getUserById(userId);

  let html = &#39;<html><body>&#39;
    + &#39;<p> userinfo: &#39; + userInfo + &#39;</p>&#39;
    + &#39;</body></html>&#39;;
  ctx.response.type =&#39;text/html&#39;;
  ctx.response.body = html;
};

var saveUserinfo = (ctx, next) => {
  const requestString = ctx.data;
  //TODO数据处理
  Console.log(requestString);
};

module.exports = {
  &#39;GET /getUserinfo&#39;: getUserinfo,
  &#39;POST /saveUserinfo&#39;: saveUserinfo
};
Copy after login

2.5. Data processing

[userService.js]

Processing encapsulation from ***Dao The data obtained by .js is returned to the Controller


const userDao = require(&#39;./../dao/userDao.js&#39;);

var getUserById = async (userId) => {
  var users = userDao.getUserById(userId);
  var responseContent = &#39;&#39;;
  for(let user of users) {
    reaponseContent += &#39;姓名:&#39; + user.name + &#39; |&#39;;
    reaponseContent += &#39;年龄:&#39; + user.age + &#39; |&#39;;
    reaponseContent += &#39;身高:&#39; + user.height + &#39;<br />&#39;;
  }
  return responseContent;
}

module.exports = {
  getUserById : getUserById
};
Copy after login

2.6. Data acquisition

[userDao.js]

Get user data by requesting incoming parameters


const mysql = require(&#39;./../utils/mysqlUtil.js&#39;);

var getUserById = async (userId) => {
  let mysqlOptions = {
    sql : &#39;select * from table_user where user_id = ?&#39;,
    args : [userId]
  };

  var users = await mysql.execQuery(mysqlOptions);
  if(users.length == 0) {
    return null;
  } else {
    return users;
  }
};

module.exports = {
  getUserById : getUserById
};
Copy after login

2.7. Database operation

[ mysqlUtil.js]

Contains database connection pool control, connection establishment and release management, and execution of database operation requests initiated by Dao


##
const mysql = require(&#39;mysql&#39;);
const config = require(&#39;./../../config/config.local.js&#39;);

var connectionPool = mysql.createPool({
  &#39;host&#39; : config.database.host,
  &#39;port&#39;:config.database.port,
  &#39;user&#39; : config.database.user,
  &#39;password&#39; : config.database.password,
  &#39;database&#39; : config.database.database,
  &#39;charset&#39;: config.database.charset,
  &#39;connectionLimit&#39;: config.database.connectionLimit,
  &#39;supportBigNumbers&#39;: true,
  &#39;bigNumberStrings&#39;: true
});

var release = connection => {
  connection.end(function(error) {
    if(error) {
      console.log(&#39;Connection closed failed.&#39;);
    } else {
      console.log(&#39;Connection closed succeeded.&#39;);
    }
  });
};

var execQuery = sqlOptions => {
  var results = new Promise((resolve, reject) => {
      connectionPool.getConnection((error,connection) => {
      if(error) {
        console.log("Get connection from mysql pool failed !");
        throw error;
      }

      var sql = sqlOptions[&#39;sql&#39;];
      var args = sqlOptions[&#39;args&#39;];

      if(!args) {
        var query = connection.query(sql, (error, results) => {
          if(error) {
            console.log(&#39;Execute query error !&#39;);
            throw error;
          }

          resolve(results);
        });
      } else {
        var query = connection.query(sql, args, function(error, results) {
          if(error) {
            console.log(&#39;Execute query error !&#39;);
            throw error;
          }

          resolve(results);
        });
      }

      connection.release(function(error) {
        if(error) {
          console.log(&#39;Mysql connection close failed !&#39;);
          throw error;
        }
      });
    });
  }).then(function (chunk) {
    return chunk;
  });

  return results;
};

module.exports = {
  release : release,
  execQuery : execQuery
}
Copy after login

Related Recommended:


Recommended 10 articles about koa2

Tutorial on using the koa2 framework in nodejs6

Share an example tutorial on using the koa2 framework in nodejs

The above is the detailed content of Node uses Koa2 to build web projects. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

How to use Nginx web server caddy How to use Nginx web server caddy May 30, 2023 pm 12:19 PM

Introduction to Caddy Caddy is a powerful and highly scalable web server that currently has 38K+ stars on Github. Caddy is written in Go language and can be used for static resource hosting and reverse proxy. Caddy has the following main features: Compared with the complex configuration of Nginx, its original Caddyfile configuration is very simple; it can dynamically modify the configuration through the AdminAPI it provides; it supports automated HTTPS configuration by default, and can automatically apply for HTTPS certificates and configure it; it can be expanded to data Tens of thousands of sites; can be executed anywhere with no additional dependencies; written in Go language, memory safety is more guaranteed. First of all, we install it directly in CentO

Real-time protection against face-blocking barrages on the web (based on machine learning) Real-time protection against face-blocking barrages on the web (based on machine learning) Jun 10, 2023 pm 01:03 PM

Face-blocking barrage means that a large number of barrages float by without blocking the person in the video, making it look like they are floating from behind the person. Machine learning has been popular for several years, but many people don’t know that these capabilities can also be run in browsers. This article introduces the practical optimization process in video barrages. At the end of the article, it lists some applicable scenarios for this solution, hoping to open it up. Some ideas. mediapipeDemo (https://google.github.io/mediapipe/) demonstrates the mainstream implementation principle of face-blocking barrage on-demand up upload. The server background calculation extracts the portrait area in the video screen, and converts it into svg storage while the client plays the video. Download svg from the server and combine it with barrage, portrait

Using Jetty7 for Web server processing in Java API development Using Jetty7 for Web server processing in Java API development Jun 18, 2023 am 10:42 AM

Using Jetty7 for Web Server Processing in JavaAPI Development With the development of the Internet, the Web server has become the core part of application development and is also the focus of many enterprises. In order to meet the growing business needs, many developers choose to use Jetty for web server development, and its flexibility and scalability are widely recognized. This article will introduce how to use Jetty7 in JavaAPI development for We

How to implement form validation for web applications using Golang How to implement form validation for web applications using Golang Jun 24, 2023 am 09:08 AM

Form validation is a very important link in web application development. It can check the validity of the data before submitting the form data to avoid security vulnerabilities and data errors in the application. Form validation for web applications can be easily implemented using Golang. This article will introduce how to use Golang to implement form validation for web applications. 1. Basic elements of form validation Before introducing how to implement form validation, we need to know what the basic elements of form validation are. Form elements: form elements are

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

How to configure nginx to ensure that the frps server and web share port 80 How to configure nginx to ensure that the frps server and web share port 80 Jun 03, 2023 am 08:19 AM

First of all, you will have a doubt, what is frp? Simply put, frp is an intranet penetration tool. After configuring the client, you can access the intranet through the server. Now my server has used nginx as the website, and there is only one port 80. So what should I do if the FRP server also wants to use port 80? After querying, this can be achieved by using nginx's reverse proxy. To add: frps is the server, frpc is the client. Step 1: Modify the nginx.conf configuration file in the server and add the following parameters to http{} in nginx.conf, server{listen80

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

See all articles