express(2)

来源:互联网 发布:淘宝产品营销方案 编辑:程序博客网 时间:2024/06/04 00:35
var http = require("http");var Application = function(){//js当中没有明确的构造器概念,都是以首字母大写来区分    //保存路由    this.router = [{        path:"*",        fn:function(req,res){            res.writeHead(404,{"Content-type":"text/plain"});            //req.method:请求的方法(get/post)            res.end("Cannot " + req.method + ' ' + req.url);        }    }];}Application.prototype = {    use:function(path,fn){//path:传入的路由名字,fn:传入的路由回调函数        this.router.push({            path:path,            fn:fn        });    },    listen:function(port){        var self = this;//区分作用域,保存thisapplication)对象        http.createServer(function(req,res){            //我需要指向谁,而这里的this又指向谁呢?            //执行到这里的时候就有必要判断路由了            for(var i = 1;i < self.router.length;i++){                if(req.url == self.router[i].path){                    return self.router[i].fn(req,res);                }            }            return self.router[0].fn(req,res);        }).listen(Number(port));//判断类型    }}exports = module.exports = Application;