search
HomeWeb Front-endJS TutorialNode uses Koa2 to build web projects

Node uses Koa2 to build web projects

Jan 15, 2018 pm 01:10 PM
koa2nodeweb

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"
}

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);

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);

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
 });

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();
};

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
};

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
};

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
};

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
}

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
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools