gpt4 book ai didi

javascript - express js :middleware function is not invoked

转载 作者:行者123 更新时间:2023-12-03 04:38:19 24 4
gpt4 key购买 nike

我正在尝试在我的express js应用程序中实现中间件功能,它遵循简单的MVC架构。

routes.js位于route文件夹

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

controllers文件夹下的auth.js

//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位于middleware文件夹

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

}
}

没有显示错误消息,但是当我访问auth路由时,不会调用中间件函数。

最佳答案

您没有正确调用它。尝试从路线调用它。

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

关于javascript - express js :middleware function is not invoked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com