2017-04-04 71 views
0

我試圖在我的express js應用程序中實現中間件功能,它遵循一個簡單的MVC體系結構。Express js:不調用中間件功能

routes.jsroute

//load the controller auth.js 
var auth = require('../controllers/auth'); 
//auth route 
router.route('/auth').get(auth.simpleAuth); 

auth.jscontrollers

//load the middleware 
var middleware = require('../middleware/middleware'); 

module.exports={ 
    simpleAuth:function (req,res) { 
     //invoke middleware 
     middleware.testMiddleware; 
     res.send('middleware test completed'); 
    } 
} 

middleware.jsmiddleware

module.exports={ 
    testMiddleware:function (req,res,next) { 
     console.log('inside middleware'); 
     if(req.username == true){ 
      next(); 
     }else{ 
      console.log('auth failed') 
     } 

    } 
} 

沒有錯誤消息是但是當我訪問auth路由時,不會調用中間件功能。

+0

請看看expressjs中間件https://expressjs.com/en/guide/using-middleware。 html –

回答

1

您沒有正確調用它。嘗試從路由中調用它。

routes.js

var middleware = require('../middleware/middleware'); 

router.route('/auth').all(middleware.testMiddleware).get(auth.simpleAuth); 

middleware.js

testMiddleware: function (req,res,next) { 
    console.log('inside middleware'); 
    if(req.username == true) { 
     next(); 
    } else { 
     // error 
     return res.status(401).json({ "message" : "auth failed"}); 
    } 
} 
+1

「全部」的含義是什麼 – Jabaa

+1

這意味着,所有類型的http請求,例如'GET','POST'將通過中間件。 –

+0

它匹配所有的HTTP動詞 –