声明: 当查询到数据库数据后,对数据库数据进行遍历,可以采用toArray()函数,具体实现可以看第六点

1、本地安装mongodb

  安装包:https://www.mongodb.com/download-center/community

2、npm安装mongodb模块

  npm install mongodb --save-dev
  npm install ejs --save-dev

3、创建express-route路由模块文件 

var url=require('url');

    //封装方法改变res  绑定res.send()
    function changeRes(res){
        res.send=function(data){
        res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});
        res.end(data);
        }
    }

    //暴露的模块
    var Server=function(){
        var G=this;   /*全局变量*/
        //处理get和post请求
        this._get={};
        this._post={};
        var app=function(req,res){
        changeRes(res);
        //获取路由
        var pathname=url.parse(req.url).pathname;
        if(!pathname.endsWith('/')){
            pathname=pathname+'/';
        }
        //获取请求的方式 get  post
        var method=req.method.toLowerCase();
        if(G['_'+method][pathname]){
            if(method=='post'){ /*执行post请求*/
            var postStr='';
            req.on('data',function(chunk){
                postStr+=chunk;
            })
            req.on('end',function(err,chunk) {
                req.body=postStr;  /*表示拿到post的值*/
                G['_'+method][pathname](req,res); /*执行方法*/
            })
            }else{ /*执行get请求*/
            G['_'+method][pathname](req,res); /*执行方法*/
            }
        }else{
            res.end('no router');
        }
        }

        app.get=function(string,callback){
        if(!string.endsWith('/')){
            string=string+'/';
        }
        if(!string.startsWith('/')){
            string='/'+string;
        }
        //    /login/
        G._get[string]=callback;
        }

        app.post=function(string,callback){
        if(!string.endsWith('/')){
            string=string+'/';
        }
        if(!string.startsWith('/')){
            string='/'+string;
        }
        G._post[string]=callback;
        }
        return app;
    }
    module.exports=Server();
View Code

相关文章: