模拟express封装node路由

express.js

var url = require('url');
//封装方法res.send()
function resSend(res){
	res.send = function(data){
		res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});
        res.end(data);
	}
}

var express_router = function(req,res){
	var G = this;
	var app = function(req,res){
		resSend(res)
		//解析请求,获取路由
		var pathname = url.parse(req.url).pathname;
		//获取请求方式
		var method = req.method.toLowerCase();
		if(G[pathname]){ 
			if(method == 'post'){
				var postStr = '';
				req.on('data',function(chunk){
					postStr+=chunk;
				})
				req.on('end',function(err,chunk){
					req.body = postStr;
					//执行方法
					G[pathname](req,res)
				})
			}
			if(method == 'get'){
				//执行方法
				G[pathname](req,res)
			}
			
		}else{
			res.end('no router')
		}
	}
	app.get = function(string,callback){
		G[string] = callback;
	}
	app.post = function(string,callback){
		G[string] = callback;
	}
	return app;
}

module.exports = express_router();

router.js

var http = require('http');
var app = require('./express.js');
http.createServer(app).listen(8001);
app.get('/',function(req,res){
	res.send('这是首页')
})
app.get('/login',function(req,res){
	res.send('login');
})
app.post('/register',function(req,res){
	res.send('register');
})

猜你喜欢

转载自blog.csdn.net/weixin_40970987/article/details/83055127
今日推荐