模拟express路由封装

1、目录结构


2、express_router.js

var url = require('url')
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 += '/';
        }
        //获取请求的方式 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方法,当以get方式提交时适用
    app.get = function(string,callback){//定义get方法
        if(!string.endsWith('/')){
            string += '/';
        }
        if(!string.startsWith('/')){
            string = '/' + string;
        }
        G._get[string] = callback;
    }
    //注册app.post方法,当以post方式提交时适用
    app.post = function(string,callback){
        if(!string.endsWith('/')){
            string += '/';
        }
        if(!string.startsWith('/')){
            string = '/' + string;
        }
        G._post[string] = callback;
    }
    return app;
}
/*
*   把模块暴露出去
*   暴露的内容是一个函数,可以放在http.createServer()函数中作为
*   形式参数,用来监听客户端发来的请求
*   Server()函数中的返回值app,就是将要暴露的内容
*   app本身是一个函数,打印出来为:[Function: app],但是,
*   因为在app身上又绑定了get方法和post方法,因此再次
*   打印app结果就变为了{ [Function: app] get: [Function], post: [Function] }
*   可知app本身即是一个函数,又可以作为一个对象作为桥梁来使用绑定于app上的post和get方法。
* */
module.exports = Server();

3、06router_express_module.js

var http = require('http')
var ejs = require('ejs')
var app = require('./model/express_router');
http.createServer(app).listen(3000);
app.get('/',function(req,res){
    var msg = 'this is the data from database';
    ejs.renderFile('./view/index.ejs',{

    },function(err,data){
        res.send(data);
    })
})

//登录页面
app.get('/login',function(req,res){
    console.log('login');
    ejs.renderFile('./views/form.ejs',{

    },function(err,data){
        res.send(data);
    })
})

//执行登录
app.post('/doLogin',function(req,res){
    console.log(req.body);
    res.send("<script>alert('登录成功');history.back();</script>")
})

app.get('/register',function(req,res){
    console.log('register')
    res.send('register')
})

app.get('/news',function(req,res){
    console.log('news')
    res.send('news information')
})

4、以debug方式运行06router_express_router.js

打断点:

以debug方式运行:

下一步:

再下一步,就跳转到了express_router.js中进行执行了,

再下一步:

再下一步:

下一步:

以此类推下一步,则所有的url得到初始化,如/,/login,/doLogin,/register,/news,此时再下一步时,图标“下一步”变灰,无法点击:

此时说明路由初始化全部完成,则此时可以访问一个路由,使得下一步可以执行,继而继续debug,现在在浏览器中访问:localhost:3000/

则如下图:则res.send(data)作为回调函数,data为ejs读取index.ejs文件得到的数据。

再下一步:

下一步:

下一步:

猜你喜欢

转载自blog.csdn.net/jiuweideqixu/article/details/86602026