简体   繁体   中英

Express js:middleware function is not invoked

i am trying to implement middle ware function in my express js application it follows a simple MVC architecture.

routes.js under route folder

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

auth.js under controllers folder

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

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

middleware.js under middleware folder

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

    }
}

There is no error message is shown but when i access auth route the middle ware function is not invoked.

You are not invoking it properly. Try calling it from route.

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"});
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM