1. 案例简介:
仿照Express路由,手动封装node路由模块。
2. 案例页面图示:
3. 案例代码结构:
4. 主要代码(server.js):
var http = require('http');
var ejs = require('ejs');
var app = require('./model/express-router');// 引入 封装路由
http.createServer(app).listen(8080); // 创建服务
app.get('/',function(req,res){ // 首页 路由
ejs.renderFile('./views/index.ejs',{},function(err,data){
if(err){
console.log('err')
}else{
res.send(data);
}
})
})
app.get('/login',function(req,res){ // 登录表单 路由
ejs.renderFile('./views/login.ejs',{},function(err,data){
if(err){
res.send('404')
}else{
res.send(data);
}
})
})
app.post('/dologin',function(req,res){ // 登录成功页 路由
let str = '';
req.on('data',function(chunk){
str += chunk;
})
req.on('end',function(err){
if(err){
res.send('404')
}else{
ejs.renderFile('./views/dologin.ejs',{
msg:str
},function(err,data){
if(err){
res.send('404')
}else{
res.send(data)
}
})
}
})
})
5. 主要代码(express-router.js 路由封装):
var url = require('url');
// 将 res.end() 封装成 res.send()
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; //全局变量
G._get = {};//分别处理get post
G._post = {};
var app = function(req,res){
changeRes(res);
var pathname = url.parse(req.url).pathname; // 获取路径
var method = req.method.toLowerCase(); // 获取请求方法
if(!pathname.endsWith('/')){
pathname = pathname + '/';
}
if(!pathname.startsWith('/')){
pathname = '/'+pathname;
}
if(G['_' + method][pathname]){
G['_' + method][pathname](req,res); //执行
}else{
res.end('no router')
}
}
app.get = function(string,callback){ // 注册get方法
if(!string.endsWith('/')){
string = string + '/';
}
if(!string.startsWith('/')){
string = '/'+string;
}
G._get[string] = callback;
}
app.post = function(string,callback){ // 注册post方法
if(!string.endsWith('/')){
string = string + '/';
}
if(!string.startsWith('/')){
string = '/'+string;
}
G._post[string] = callback;
}
return app;
}
module.exports = Server();
6. 下载源码