首页 > Web开发 > 详细

nodejs之路由

时间:2019-02-19 12:23:45      阅读:135      评论:0      收藏:0      [点我收藏+]

声明:在写nodejs代码的时候,很多模块可以封装保存起来,以后的项目都会用到。

1、路由模块

技术分享图片
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

2、直接摘抄,然后创建一个文件运行下面的代码

方式一:
    var http = require(http);
    var app = require(./express-route);
    http.createServer(app).listen(8001);

    app.get(login,function (req,res) {
        console.log(login);
        res.end(login);
    })

    app.get(register,function (req,res) {
        console.log(register);
        res.end(register);
    })

方式二:
    var http = require(http);
    var url = require(url);
    var path = require(path);
    var app = require(./module/express-route);
    var ejs = require(ejs);
    http.createServer(app).listen(8001);

    app.get(/,function (req,res) {
        var msg = route test;
        ejs.renderFile(练习/views/index.ejs,{msg:msg},function (err,data) {
            if(err){
                console.log(err);
                return false;
            }
            console.log(data);
            //服务器端有数据返回到客户端 这个时候必须用res.send()。
            //如果没有数据返回到客户端,res.send()和res.end()效果一样。
         res.send(data);
        })
    })

 

nodejs之路由

原文:https://www.cnblogs.com/ywjfx/p/10399967.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!