我创建了一个身份验证中间件来对我的路由进行身份验证。我希望在某些特定路由上不要调用中间件。有一种接受路径参数的路由,它在不调用中间件的情况下也可以正常工作,但是当我从url中删除路径参数时,它仍然调用中间件。下面是代码
var authRouter = require('../../../middlewares/authmiddleware');
router.use(authRouter);
router.post('/', controller.create);
router.put('/getUser/:id', controller.getUser);
router.get('/', authRouter, controller.getTest);
router.put('/logout', authRouter, controller.logout);
我也做了类似的事情
router.post('/', controller.create);
router.put('/getUser/:id', controller.getUser);
var authRouter = require('../../../middlewares/authmiddleware');
router.use(authRouter);
router.get('/', controller.getTest);
router.put('/logout', controller.logout);
未提供路径参数时,它将调用中间件。如果URL中未提供路径参数,我不想调用中间件。如何实现呢?
答案 0 :(得分:0)
有两种方法可以解决此问题。
authRouter
中本身,检查是否存在参数。基于此,您可以继续使用下一个中间件或调用下一条为您处理错误的路由。
authRouter = (req, resp, next) => {
if (!request.params.someparams) {
next('route'); //proceed with next route which handle error/required stuff
}
//proceed here
}
在authRouter
router.get('/', (req, resp, next) => {
if (!request.params.someparams) {
next('route'); //proceed with next route which handle error/required stuff
} else {
next(); //call next middleware
}
}, authRouter, controller.getTest);