nodejs之路由

声明:在写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);
        })
    })
原文地址:https://www.cnblogs.com/ywjfx/p/10399967.html