首页 >web前端 >js教程 >node使用Koa2搭建web项目

node使用Koa2搭建web项目

小云云
小云云原创
2018-01-15 13:10:572194浏览

本文主要介绍了node使用Koa2搭建web项目的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧,希望能帮助到大家。

随着Node.js的日益火热,各种框架开始层出不穷的涌现出来,Node.js也开始逐渐的被应用到处理服务端请求的场景中。搭建Web项目的框架也随之开始出现——express、koa、koa2、egg等,当然要了解其好坏还是要自己去啃源码的。本文将不会涉及到源码,只是带领初学者简单了解下Koa2的基本使用,欢迎大家在评论中互相交流学习。

注意:koa2使用了ES7的语法,所以使用时请升级Node版本到最新。了解更详细的源码信息可以到git上的koajs/koa去了解

1. 项目目录结构

2. 代码逻辑解析

2.1. 包结构文件

[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. 启动入口文件

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

如果请求的报文体是XML格式,可以添加下面的代码自动解析报文(注意引用koa-xxx的版本要与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的文件,这个文件是完成前端请求到具体处理方法的路由过程

2.3. 路由器文件

[router2controller.js]

该类将会自动扫描controller文件夹中的文件来加载请求映射,不需要挨个请求单独配置

koa-router原生提供方法如下:


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

自动扫描controller包实现方法如下


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. 控制器

[userController.js]

***Controller.js是用来处理具体请求信息以及返回数据的,userController.js中处理了GET请求获取用户信息,POST请求保存用户信息


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. 数据处理

[userService.js]

处理封装从***Dao.js获取到的数据返回给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. 数据获取

[userDao.js]

通过请求传入参数来获取user数据


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. 数据库操作

[mysqlUtil.js]

包含了数据库连接池控制,连接建立、释放管理,执行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
}

相关推荐:

有关koa2的文章推荐10篇

nodejs6中使用koa2框架的教程

分享nodejs中使用koa2框架的实例教程

以上是node使用Koa2搭建web项目的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn