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);
        })
    })

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM