1、示例代码05router_express.js(粗略)
var G = [];
var app = function(req,res){//定义函数app
if(G['login']){//判断方法是否存在
G['login'](req,res); /*执行注册的方法*/
}
}
//定义一个get方法
app.get=function(string, callback){
G[string] = callback;//实例化G[string]
//注册方法
}
//调用这个已经定义的方法(调用执行初始化)
app.get('login',function(req,res){
console.log('login' + req);
})
setTimeout(function(){
app('req','res');//执行函数app
},1000);
2、示例代码06router_express.js(详细)
var G = [];
var http = require('http')
var url = require('url')
/*
* 因为http.createServer(app).listen(3000);,所以3000端口中app函数作为监听函数
* 有请求来时,会执行app方法,因为判断存在G[pathname]方法则调用
* */
var app = function(req,res){//定义函数app
var pathname = url.parse(req.url).pathname;
//此时的pathname打印出来是这种格式,如/favicon.ico
if(!pathname.endsWith('/')){//在末尾加上一个斜杠,因为
pathname=pathname+'/';
}
//此时pathname变为这种格式,如/favicon.ico/(两边都加上了斜杠,这和已经注册过的方法是遥相呼应的)
if(G[pathname]){//如果函数存在的话就进行调用
G[pathname](req,res);
}else{//函数G[pathname]不存在的话,说明没有这个路由
res.end('no router');
}
}
//定义一个get方法(把传入的callback方法赋值给G[string])
app.get=function(string, callback){
if(!string.endsWith('/')){
string += '/';
}
if(!string.startsWith('/')){
string = '/' + string;
}
/*
* 然后路由会变成这种形式(两边都加上了斜杠)
* /login/ 、 /register/
* */
console.log(string)
/*
* 把callback方法赋值给G[string]
* */
G[string] = callback;
}
//只要有请求,就会触发app这个方法
http.createServer(app).listen(3000);
/*
* 调用这个已经定义的方法(调用执行初始化)
* 没有请求时,相当于对方法进行了声明
* */
//注册login这个路由(在访问之前就已经完成了注册)
app.get('login',function(req,res){
console.log('login');
res.end('login');
})
app.get('register',function(req,res){
console.log('register')
res.end('register')
})