Home > Article > Web Front-end > Node uses Koa2 to build web projects
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);
[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 });
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(); };
[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 = '<html><body>' + '<p> userinfo: ' + userInfo + '</p>' + '</body></html>'; ctx.response.type ='text/html'; ctx.response.body = html; }; var saveUserinfo = (ctx, next) => { const requestString = ctx.data; //TODO数据处理 Console.log(requestString); }; module.exports = { 'GET /getUserinfo': getUserinfo, 'POST /saveUserinfo': saveUserinfo };
[userService.js]
Processing encapsulation from ***Dao The data obtained by .js is returned to the Controller
const userDao = require('./../dao/userDao.js'); var getUserById = async (userId) => { var users = userDao.getUserById(userId); var responseContent = ''; for(let user of users) { reaponseContent += '姓名:' + user.name + ' |'; reaponseContent += '年龄:' + user.age + ' |'; reaponseContent += '身高:' + user.height + '<br />'; } return responseContent; } module.exports = { getUserById : getUserById };
[userDao.js]
Get user data by requesting incoming parameters
const mysql = require('./../utils/mysqlUtil.js'); var getUserById = async (userId) => { let mysqlOptions = { sql : 'select * from table_user where user_id = ?', args : [userId] }; var users = await mysql.execQuery(mysqlOptions); if(users.length == 0) { return null; } else { return users; } }; module.exports = { getUserById : getUserById };
[ mysqlUtil.js]
Contains database connection pool control, connection establishment and release management, and execution of database operation requests initiated by Dao
const mysql = require('mysql'); const config = require('./../../config/config.local.js'); var connectionPool = mysql.createPool({ 'host' : config.database.host, 'port':config.database.port, 'user' : config.database.user, 'password' : config.database.password, 'database' : config.database.database, 'charset': config.database.charset, 'connectionLimit': config.database.connectionLimit, 'supportBigNumbers': true, 'bigNumberStrings': true }); var release = connection => { connection.end(function(error) { if(error) { console.log('Connection closed failed.'); } else { console.log('Connection closed succeeded.'); } }); }; 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['sql']; var args = sqlOptions['args']; if(!args) { var query = connection.query(sql, (error, results) => { if(error) { console.log('Execute query error !'); throw error; } resolve(results); }); } else { var query = connection.query(sql, args, function(error, results) { if(error) { console.log('Execute query error !'); throw error; } resolve(results); }); } connection.release(function(error) { if(error) { console.log('Mysql connection close failed !'); 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!