zoukankan      html  css  js  c++  java
  • Nodejs 路由模块封装、封装仿照 express 的路由(9)

    1、 模块化的方式封装

    `model/model.js`

     

    // 导入模块
    var ejs=require('ejs');
    
    var fs=require('fs');
    
    var app ={
        // login
        login:function (req, res) {
            console.log('login');
            ejs.renderFile('views/form.ejs',{},function (err,data) {
                res.end(data);
            })
        },
        // dologin
        dologin:function (req, res) {
            console.log('333dologin');
    
            var postStr = '';
            req.on('data',function (chunk) {
                postStr+= chunk;
            });
            req.on('end',function (err,chunk) {
                console.log(postStr);
                fs.appendFile('login.txt',postStr+'
    ',function (err) {
                    if (err){
                        console.log(err);
                        return false;
                    }
                    console.log('写入成功')
                });
                res.end("<script>alert('登录成功');history.back();</script>")
            });
        },
        // register
        register:function (req, res) {
            console.log('register');
            res.end('register')
        },
        home:function (req, res) {
            console.log('home');
            res.end('home')
        }
    };
    
    // 暴露
    module.exports=app;
    
    /*
    调用方式
    app.login(req,res)
    app['login'](req,res)
     */

    ` 01 services.js`

    //引入http模块
    var http=require('http');
    var url =require('url');
    
    // 导入自己封装的路由
    var model = require('./model/model');
    
    //路由:指的就是针对不同请求的 URL,处理不同的业务逻辑。
    http.createServer(function(req,res){
        // http://localhost:8001/login
        res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});
        var pathname = url.parse(req.url).pathname.replace('/','')
        console.log(pathname);
    
        // 调用路由,处理逻辑 
        if (pathname!=='favicon.ico'){
            try{
                model[pathname](req,res);
            }catch (err) {
                model['home'](req,res)
            }
        }
    
    }).listen(8001);

    2、 封装仿照 express 的路由

    1、nodejs 万事万物皆为对象

      构建一个app对象,可以再绑定属性和方法

    var app=function(){
    
        console.log('app');
    }
    
    app.get=function(){
        console.log('app.get');
    }
    app.post=function(){
        console.log('app.post');
    }
    
    
    app.post() /*app.post*/
    
    //
    app()   /*app*/

    2 仿照 express,封装路由

    ```

    代码执行顺序: 从上到下

    ```

    var G ={};
    
    var app =function (req, res) {
        if (G['login']){
            G['login'](req,res);/*执行注册方法*/
        }
    };
    
    // 定义一个get 方法
    app.get = function (string, callback) {
        G[string]=callback // G[string] = 函数
    };
    
    // 执行get方法 login 页面的处理逻辑
    app.get('login',function (req, res) {
        console.log('login'+req)
    });
    
    // 程序开始执行 setTimeout(
    function () { app('req','res') },1000);

    再次升级 `03 router_express_2.js` 

    var http=require('http');
    var url= require('url');
    var G ={};
    
    var app =function (req, res) {
        var pathname = url.parse(req.url).pathname.replace('/','');
        console.log(pathname);
        if (G[pathname]){
            G[pathname](req,res);
        }
    
        // if (G['login']){
        //     G['login'](req,res);/*执行注册方法*/
        // }
    };
    
    // 定义一个get 方法
    app.get = function (string, callback) {
        G[string]=callback // G[string] = 函数
    };
    
    
    // 只需要请求,就会触发app这个方法
    http.createServer(app).listen(8001);
    
    // 注册login 路由
    app.get('login',function (req, res) {
        console.log('login');
        res.end('login');
    });
    
    // 注册 register 路由
    app.get('register',function (req, res) {
        console.log('register');
        res.end('register');
    });

    最后的封装

    `model/express_router.js`

    var url = require('url');
    
    // 封装 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) {
            // res 封装send方法
            changeRes(res);
    
            var pathname = url.parse(req.url).pathname.replace('/','');
            var method = req.method.toLowerCase();
            console.log(method,pathname);
            console.log(G['_'+method]);
    
            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;
                        G['_'+method][pathname](req,res); /*执行方法*/
                        // res.end(pathname)
                    })
                }else{ /* 处理非 post 请求 */
                    G['_'+method][pathname](req,res)
                    // res.end(pathname)
    
                }
            }else{
                res.end('no router!')
            }
        };
    
        // 注册方式
        app.get=function (string, callback) {
            console.log( G._get[string],string);
    
            G._get[string]=callback
        };
    
        app.post=function (string, callback) {
            G._post[string]=callback
        };
        return app
    };
    
    module.exports = Server();

    执行程序 `router_express_module.js`

    var http = require('http');
    var ejs = require('ejs');
    var app = require('./model/express_router.js');
    console.log(app);
    
    http.createServer(app).listen(8001);
    
    //登录页面
    app.get('login',function(req,res){
    
        ejs.renderFile('views/form.ejs',{},function(err,data){
    
            res.send(data);
        })
    
    });
    app.post('dologin',function (req, res) {
        res.send("<script>alert('successful !');history.back();</script>")
    });
    
    app.get('news',function (req, res) {
        res.send("国际大新闻")
    });
  • 相关阅读:
    zookeeper使用场景
    zookeeper安装配置
    hadoop 远程调试
    deep learning笔记
    Sentiment Analysis(1)-Dependency Tree-based Sentiment Classification using CRFs with Hidden Variables
    PRML阅读笔记 introduction
    Python 学习笔记(2)
    python nltk 学习笔记(5) Learning to Classify Text
    python nltk 学习笔记(4) Writing Structured Programs
    python nltk 学习笔记(3) processing raw text
  • 原文地址:https://www.cnblogs.com/angle6-liu/p/11742476.html
Copyright © 2011-2022 走看看