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

Node uses Koa2 to build web projects

小云云
Release: 2018-01-15 13:10:57
Original
2192 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template