express-route.jsvarurl=require('url');functionchangeRes(res){res.send=function(data){res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});res.end(数据);}}varServer=function(){varG=this;这个._get={};这个._post={};varapp=function(req,res){changeRes(res);varpathname=url.parse(req.url).pathname;if(!pathname.endsWith('/')){pathname=pathname+'/';}varmethod=req.method.toLowerCase();//if(G['_'+method][pathname]){if(G['_'+method][pathname]){if(method=='post'){varpostStr='';req.on('data',function(chunk){postStr+=chunk;})req.on('end',function(err,chunk){req.body=postStr;G['_'+method][路径名](req,res);})}else{G['_'+方法][pathname](req,res);}}else{res.end('没有路由器');}}app.get=function(string,callback){if(!string.endsWith('/')){string=string+'/'}if(!string.startsWith('/')){string='/'+字符串;}G._get[string]=回调;}app.post=function(string,callback){if(!string.endsWith('/')){string=string+'/'}if(!string.startsWith('/')){string='/'+字符串;}G._post[string]=回调;}returnapp;}module.exports=Server();index2.jsvarhttp=require('http');varejs=require('ejs');varapp=require('./model/express-route');console.log(app);http.createServer(app).listen(3000);app.get('/',function(req,res){varmsg='这是数据库里的数据';ejs.renderFile('views/index.ejs',{msg:msg},function(err,data){res.send(data);})})app.get('/login',function(req,res){ejs渲染文件('views/form.ejs',{},function(err,data){res.send(data);})})app.post('/dologin',function(req,res){console.log(req.body);res.send("");})app.get('/register',function(req,res){console.log('register')res.send('register');})app.get('/news',function(req,res){console.log('news')res.send('news');})解析http.createServer(app).listen(3000);相当于http.createServer(function(req,res){changeRes(res);varpathname=url.parse(req.url).pathname;if(!pathname.endsWith('/')){pathname=pathname+'/';}varmethod=req.method.toLowerCase();//if(G['_'+method][pathname]){if(G['_'+method][pathname]){if(method=='post'){varpostStr='';req.on('data',function(chunk){postStr+=chunk;})req.on('end',function(err,chunk){req.body=postStr;G['_'+me方法][路径名](req,res);})}else{G['_'+方法][路径名](req,res);}}else{res.end('没有路由器');}}).listen(3000);
