node mysql 模块化_node笔记(八)-Nodejs 路由封装 模块化方式封装

express-route.js

var url = require('url');

function changeRes(res){

res.send= function(data){

res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"});

res.end(data);

}

}

var Server = function(){

var G = this;

this._get = {};

this._post = {};

var app = function(req,res){

changeRes(res);

var pathname = url.parse(req.url).pathname;

if(!pathname.endsWith('/')){

pathname = pathname + '/';

}

var method = req.method.toLowerCase();

// if(G['_'+ method][pathname]){

if(G['_'+ method][pathname]){

if(method == 'post'){

var postStr = '';

req.on('data',function(chunk){

postStr += chunk;

})

req.on('end',function(err,chunk){

req.body = postStr;

G['_'+method][pathname](req,res);

})

}else{

G['_'+method][pathname](req,res);

}

}else{

res.end('no router');

}

}

app.get = function(string,callback){

if(!string.endsWith('/')){

string = string+'/'

}

if(!string.startsWith('/')){

string = '/'+ string;

}

G._get[string] = callback;

}

app.post = function(string,callback){

if(!string.endsWith('/')){

string = string+'/'

}

if(!string.startsWith('/')){

string = '/'+ string;

}

G._post[string] = callback;

}

return app;

}

module.exports = Server();

index2.js

var http = require('http');

var ejs = require('ejs');

var app = require('./model/express-route');

console.log(app);

http.createServer(app).listen(3000);

app.get('/',function(req,res){

var msg = '这是数据库里的数据';

ejs.renderFile('views/index.ejs',{msg:msg},function(err,data){

res.send(data);

})

})

app.get('/login',function(req,res){

ejs.renderFile('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);

var pathname = url.parse(req.url).pathname;

if(!pathname.endsWith('/')){

pathname = pathname + '/';

}

var method = req.method.toLowerCase();

// if(G['_'+ method][pathname]){

if(G['_'+ method][pathname]){

if(method == 'post'){

var postStr = '';

req.on('data',function(chunk){

postStr += chunk;

})

req.on('end',function(err,chunk){

req.body = postStr;

G['_'+method][pathname](req,res);

})

}else{

G['_'+method][pathname](req,res);

}

}else{

res.end('no router');

}

}).listen(3000);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值