nodejs koa web搭建

平台 :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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值