聽說中間件還挺重要,下面梳理一下初認識:
中間件是什么?簡單說說http請求服務的過濾,當交給函數處理之前先交給它處理。匹配后會終止,要想再匹配,得加: next.
中間件能解決什么問題?檢測用戶登錄 / 檢測RBAC曲線 等等
例子:
app.use('/',function(req,res,next){
console.log('1');
next(); //重要代碼
}
app.get('./stu',function(req,res){
console.log('stu index');
res.send('stu index')
}
這個在輸出的時候會輸出1,再輸出stu index。
如果
app.use('/',function(req,res,next){
console.log('1');
}
app.get('./stu',function(req,res){
console.log('stu index');
res.send('stu index')
}
則只輸出1,不會往下執行了。
第二個大作用,可以過濾錯誤,對所有錯誤做統一處理:err,req,res,next 這些參數有些可以不寫,但是順序不能亂。
app.get('./stu',function(err,req,res,next){
if(err) next(err)
.....
}
app.get('./stu/created',function(err,req,res,next){
if(err) next(err)
.....
}
在最后統一處理err,解放程序員雙手,不繁瑣
app.use('/', function(err,req,res,next){
res.send('網絡異常。。。') //要改提示信息在這里改即可:res.send('網絡異常,請稍后重試')
}