码迷,mamicode.com
首页 > Web开发 > 详细

nodejs之路由

时间:2019-02-19 11:43:42      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:var   OLE   close   hunk   color   lis   tst   har   ack   

声明:在写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‘);
})

 

nodejs之路由

标签:var   OLE   close   hunk   color   lis   tst   har   ack   

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

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!