With the increasing heat of node. js, the various frameworks are beginning to emerge, and node. JS is gradually being applied to the scenario that handles server-side requests. The framework for building Web projects also began to appear--express, KOA, KOA2, egg, and so on, of course, to understand its good or bad or to eat their own source. This article will not be involved in the source code, just lead beginners to understand the basic use of KOA2, welcome everyone in the comments exchange learning.
Note: KOA2 uses the ES7 syntax, so please upgrade the node version to the latest when you use it.
Learn more about the source information can be koajs/koa to git to understand.
1. Project directory Structure
2. Code Logic Parsing
2.1. Package Structure File
{ "name": "Weixin-node-koa", "version": "1.0.0", "description": "Node. js With Koa2 ", 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. Launch the Portal file
App.js
Const KOA = require (' Koa 'new= require ('./app/router2controller.js '= 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 style is an XML format, you can add the following code to automatically parse the message (note that the version of the reference koa-xxx is to correspond to KOA2)
Const KOA = require (' Koa ' = new Koa (); const Router2controller = require ('./app/router2controller.js ') Span style= "color: #000000"), const config = require ('./config/config.local.js ' // start received XML data request separate parse store const XMLPARSER = require (' koa-xml-body '
From the code see introduced a router2controller.js file, which is to complete the front-end request to the specific processing method of the routing process
2.3. Router files
Router2controller.js, the class will automatically scan the files in the Controller folder to load the request mappings, without having to request a separate configuration
Koa-router Native 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});
Automatic Scan controller Package implementation method is as follows
Const FS = require (' FS '); Const router= Require (' Koa-router ')();functionaddmapping (Router, mapping) { for(varwr.inchmapping) { if(Url.startswith (' GET ')) { varPath = url.substring (4); Router.get (path, Mapping[url]); Console.log (' Register URL mapping:get ${path} '); } Else if(Url.startswith (' POST ')) { varPath = url.substring (5); Router.post (path, Mapping[url]); Console.log (' Register URL mapping:post ${path} '); } Else if(Url.startswith (' PUT ')) { varPath = url.substring (4); Router.put (path, Mapping[url]); Console.log (' Register URL mapping:put ${path} '); } Else if(Url.startswith (' DELETE ')) { varPath = url.substring (7); Router.del (path, Mapping[url]); Console.log (' Register URL mapping:delete ${path} '); } Else{console.log (' Invalid URL: ${url} '); } }}functionaddcontrollers (Router, dir) {Fs.readdirsync (__dirname+ '/' + dir). Filter ((f) = { returnF.endswith ('. js ')); }). ForEach ((f)={console.log (' Process controller: ${f} ... '); Let mapping= require (__dirname + '/' + dir + '/' +f); Addmapping (router, mapping); });} Module.exports=function(dir) {varControllersdir = Dir | | ' Controller '; Addcontrollers (router, controllersdir); returnrouter.routes ();};
2.4. Controller
Usercontroller.js,***controller.js is used to process specific request information and return data, usercontroller.js processing a GET request to obtain user information, POST request to save user information
Const USERSERVICE = require ('./... /service/userservice.js ');varGetUserInfo = (CTX, next) = ={Let query=Ctx.query; Let UserId=query.id; Let UserInfo=Userservice.getuserbyid (userId); Let HTML= ' ; Ctx.response.type= ' text/html '; Ctx.response.body=html;};varSaveuserinfo = (CTX, next) = ={Const requeststring=Ctx.data; //TODO Data processingConsole.log (requeststring);}; Module.exports= { ' Get/getuserinfo ': GetUserInfo,' Post/saveuserinfo ': Saveuserinfo};
2.5. Data processing
Userservice.js, processing encapsulates the data obtained from the ***dao.js returned to the controller
Const USERDAO = require ('./... /dao/userdao.js ');varGetuserbyid = Async (UserId) = { varUsers =Userdao.getuserbyid (userId); varResponsecontent = ' '; for(let user of users) {reaponsecontent+ = ' Name: ' + user.name + ' | '; Reaponsecontent+ = ' Age: ' + user.age + ' | '; Reaponsecontent+ = ' Height: ' + user.height + ' <br/> '; } returnresponsecontent;} Module.exports={Getuserbyid:getuserbyid};
2.6. Data acquisition
Userdao.js, obtaining user data by requesting incoming parameters
Const MySQL = require ('./... /utils/mysqlutil.js ');varGetuserbyid = Async (UserId) ={Let mysqloptions={sql:' SELECT * from table_user where user_id =? ', args: [UserId]}; varUsers =await Mysql.execquery (mysqloptions); if(Users.length = = 0) { return NULL; } Else { returnusers; }};module.exports={Getuserbyid:getuserbyid};
2.7. Database operations
Mysqlutil.js, including database connection pool control, connection establishment, release management, execution of DAO initiated database operation requests
Const MySQL = require (' MySQL '); Const config= Require ('./... /.. /config/config.local.js ');varConnectionPool =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});varRelease = Connection = ={connection.end (function(Error) {if(Error) {Console.log (' Connection closed failed. '); } Else{Console.log (' Connection closed succeeded. '); } });};varExecQuery = sqloptions = = { varResults =NewPromise (Resolve, reject) ={connectionpool.getconnection (error,connection)= { if(Error) {Console.log ("Get connection from MySQL pool failed!"); Throwerror; } varsql = sqloptions[' sql ']; varargs = sqloptions[' args ']; if(!args) { varquery = Connection.query (sql, (error, results) = = { if(Error) {Console.log (' Execute query Error! '); Throwerror; } resolve (results); }); } Else { varquery = connection.query (sql, args,function(Error, results) {if(Error) {Console.log (' Execute query Error! '); Throwerror; } resolve (results); }); } connection.release (function(Error) {if(Error) {Console.log (' Mysql connection close failed! '); Throwerror; } }); }); }). Then (function(chunk) {returnChunk; }); returnresults;}; Module.exports={release:release, execquery:execquery}
This instance I did not tidy up and run in this machine, but the idea of this package structure is worth learning, the whole example code see http://bijian1013.iteye.com/blog/2425085.
Article Source: 68060551
Build a Web project using KOA2