Nodejs封裝類似express框架的路由實例詳解
更新時間:2020年01月05日 11:25:00 作者:loaderman
在本篇文章里小編給大家整理的是關于Nodejs封裝類似express框架的路由實例內容,有需要的朋友們學習下。
代碼如下
var http=require('http');
var ejs=require('ejs');
var app=require('./model/express-route.js');
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){
console.log('login');
ejs.renderFile('views/form.ejs',{},function(err,data){
res.send(data);
})
})
//執(zhí)行登錄
app.post('/dologin',function(req,res){
console.log(req.body); /*獲取post傳過來的數據*/
res.send("<script>alert('登錄成功');history.back();</script>")
})
app.get('/register',function(req,res){
console.log('register');
res.send('register');
})
app.get('/news',function(req,res){
console.log('register');
res.send('新聞數據');
})
express-route.js
var url=require('url');
//封裝方法改變res 綁定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; /*全局變量*/
//處理get和post請求
this._get={};
this._post={};
var app=function(req,res){
changeRes(res);
//獲取路由
var pathname=url.parse(req.url).pathname;
if(!pathname.endsWith('/')){
pathname=pathname+'/';
}
//獲取請求的方式 get post
var method=req.method.toLowerCase();
if(G['_'+method][pathname]){
if(method=='post'){ /*執(zhí)行post請求*/
var postStr='';
req.on('data',function(chunk){
postStr+=chunk;
})
req.on('end',function(err,chunk) {
req.body=postStr; /*表示拿到post的值*/
//G._post['dologin'](req,res)
G['_'+method][pathname](req,res); /*執(zhí)行方法*/
})
}else{ /*執(zhí)行get請求*/
G['_'+method][pathname](req,res); /*執(zhí)行方法*/
}
}else{
res.end('no router');
}
}
app.get=function(string,callback){
if(!string.endsWith('/')){
string=string+'/';
}
if(!string.startsWith('/')){
string='/'+string;
}
// /login/
G._get[string]=callback;
}
app.post=function(string,callback){
if(!string.endsWith('/')){
string=string+'/';
}
if(!string.startsWith('/')){
string='/'+string;
}
// /login/
G._post[string]=callback;
//G._post['dologin']=function(req,res){
//
//}
}
return app;
}
module.exports=Server();
以上代碼很簡單,大家可以測試下,如果有任何疑問和補充可以聯(lián)系小編,更多內容可以查看以下相關知識點。
您可能感興趣的文章:
- Express的路由詳解
- 詳解NodeJS框架express的路徑映射(路由)功能及控制
- 詳解nuxt路由鑒權(express模板)
- nodejs開發(fā)——express路由與中間件
- 基于express中路由規(guī)則及獲取請求參數的方法
- nodeJS?express路由學習req.body與req.query方法實例詳解
- vue路由history模式頁面刷新404解決方法Koa?Express
- Node Express用法詳解【安裝、使用、路由、中間件、模板引擎等】
- nodejs?express路由匹配控制及Router模塊化使用詳解
- 淺探express路由和中間件的實現
- NodeJs?Express路由使用流程解析
- Express框架定制路由實例分析
相關文章
利用nginx + node在阿里云部署https的步驟詳解
這篇文章主要給大家介紹了關于利用nginx + node在阿里云部署https的步驟,文中通過圖文及示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧。2017-12-12
完美解決node.js中使用https請求報CERT_UNTRUSTED的問題
下面小編就為大家?guī)硪黄昝澜鉀Qnode.js中使用https請求報CERT_UNTRUSTED的問題。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01

