nodejs koa web搭建

来源:互联网 发布:淘宝现金券 编辑:程序博客网 时间:2024/06/08 14:36

平台 :windows
node version : >=v7.6.0

$ npm i koa$ node my-koa-app.js

git地址:https://gitee.com/pmj_19950812/ruishipmjNode.git

1.创建路由
var router = require(‘koa-router’)();
router.get(‘/routeName’, async func);
app.use(router.routes());
app.listen(port, callbackFunc);

2.把module加载进属性

/** * 把指定文件加载成路由 * @param {*} routePath 路径 * @param {*} routeObj async 函数 * @param {*} file 文件名 */var loadUrl = (routePath, routeObj, file) => {    for (var key in routeObj) {        var urlInfo = key.split('_');        var method = config.httpDefaultMethod;        var action = '';        var param = '';        if (urlInfo.length == 1) {            action = routePath + '/' + key;        } else if (urlInfo.length == 2) {            action = routePath + '/' + urlInfo[0];            method = urlInfo[1];        }        let have = false;        if (method == 'get') {            for (let i = 0; i < haveGetUrl.length; i++){                if (haveGetUrl[i] == action){                    have = true;                }            }            if (!have) {                haveGetUrl.push(action);            } else {                var errObj = {'errAction': action, 'errWay': __dirname + routePath + '\\' + file};                errUrl.push(errObj);                return;            }            router.get(action, routeObj[key]);        } else if (method == 'post') {            for (let i = 0; i < havePostUrl.length; i++){                if (havePostUrl[i] == action){                    have = true;                }            }            if (!have) {                havePostUrl.push(action);            } else {                var errObj = {'errAction': action, 'errWay': __dirname + routePath + '\\' + file};                errUrl.push(errObj);                return;            }            router.post(action, routeObj[key]);        }        console.log('auto map route -> [%s]%s', method, action);    }}

3.增加根据文件的路径添加路由

var readDirFun = (filePath) =>{    var readDir = fs.readdirSync(router_path + filePath);    readDir.forEach( file => {        //如果是文件夹        if (file.indexOf('.') == -1){            if ( !(file == 'help')){                readDirFun(filePath + '/' + file);                return;            } else {                return;            }        }        //这里可以加入你想排除的路由        if(file.endsWith('.js') < 0 || file == TAG || file == 'httpServer2.js' || file.endsWith('Help.js')){            return;        } else {            loadUrl(filePath, require(router_path + filePath + '/' + file), file);        }    })};

4.添加http请求的参数处理

const bodyParser = require('koa-bodyparser');app.use(bodyParser());

这个代码必须在router加载之前,处理get,post请求的参数,创建迭代器,把所有请求的参数都绑定在ctx.msg上便于处理请求

app.use(async (ctx, next) =>{    if (ctx.request.method == 'GET') {        ctx.msg = ctx.request.query;    } else if (ctx.request.method == 'POST') {        ctx.msg = await parse.json(ctx);    }    ctx.body = {};    try {        await next();        if (ctx.conn)            await ctx.conn.commit();    } catch (ex) {        if (ctx.conn)            ctx.conn.rollback();        ctx.body = {            success: false,            msg: ex.message        }    } finally {        if (ctx.conn)            ctx.conn.release();    }});

测试代码:

"use strict"function test(){}test.prototype.test_get = async ctx => {    console.log('test');} module.exports = new test();

测试结果:
@pmj

原创粉丝点击