这一节主要记录下简单的路由封装,这样代码的可读性也增强了,代码也不会显得那么冗余。
这里为了代码查看方便, 我将所有代码放在一个文件中, 开发的时候, 我们会将app模块 module.exports 出去, 这样我们只要var app = require(‘地址’);就可以拿到使用了。
var http = require('http');
var url = require('url');
var G = {}; // 用来存放路由的对象
var app = function(req,res){
var pathname = url.parse(req.url).pathname;
// 为了存储读取方便, 我们统一设定G中的属性名格式为: /value/
if(!pathname.endsWith('/')){
pathname = pathname + '/';
}
if(G[pathname]){
G[pathname](req, res);
}else {
res.end('no this router');
}
}
// http.createServer(function(req,res){}) => 将function(req,res){}提
//出来定义为一个函数app
http.createServer(app).listen(8003);
app.get = function(string, callback){
// 为了存储读取方便, 我们统一设定G中的属性名格式为: /value/
if(!string.startsWith('/')){
string = '/' + string;
}
if(!string.endsWith('/')){
string = string + '/';
}
G[string] = callback;
}
app.get('login', function(req, res){
console.log('app.get login');
res.end('login');
})
app.get('register', function(req, res){
console.log('app.get register');
res.end('register');
})