首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从中间件返回中间件

从中间件返回中间件
EN

Stack Overflow用户
提问于 2018-07-25 18:32:03
回答 1查看 1K关注 0票数 1

我正在使用快件-验证器,并且希望根据请求体中的值进行不同的检查。

我已经为此创建了一个函数,但我没有得到任何回复(即,快递只是挂起):

validation/profile.js

代码语言:javascript
复制
module.exports = function (req,res,next) {
    if (req.body.type == 'teacher') {
        return check('name').exists().withMessage('Name is required'),
    } else {
        return check('student_id').exists().withMessage('Student id is required'),
    }
}

app.js

代码语言:javascript
复制
router.put('/', require('./validation/profile'), (req, res, next) => {
    const errors = validationResult(req).formatWith(errorFormatter)
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.mapped() })
    } else {
        res.send(req.user)
    }  
})

但是,如果我将我的函数写成一个普通函数(而不是像中间件那样有3个params)并调用它,那么它都能工作。但是这样,我将无法访问请求对象。我得“硬编码”帕拉姆。

validation/profile.js

代码语言:javascript
复制
module.exports = function (type) {
    if (type == 'teacher') {
        return check('name').exists().withMessage('Name is required'),
    } else {
        return check('student_id').exists().withMessage('Student id is required'),
    }
}

app.js

代码语言:javascript
复制
router.put('/', require('./validation/profile')('teacher'), (req, res, next) => {
    const errors = validationResult(req).formatWith(errorFormatter)
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.mapped() })
    } else {
        res.send(req.user)
    }  
})

对于如何根据请求体中的值实现不同的检查,有什么建议吗?

EN

回答 1

Stack Overflow用户

发布于 2018-07-25 19:05:55

express-validator 检查API创建中间件,您应该将它直接附加到表达式中,或者像express那样自己调用它。

代码语言:javascript
复制
// Use routers so multiple checks can be attached to them.

const teacherChecks = express.Router();
teacherChecks.use(check('name').exists().withMessage('Name is required'));

const studentChecks = express.Router();
studentChecks .use(check('student_id').exists().withMessage('Student id is required'));

module.exports = function (req,res,next) {
    if (req.body.type == 'teacher') {
        teacherChecks(req, res, next);
    } else {
        studentChecks(req, res, next);
    }
}

您还可以使用oneOf来做同样的事情。

代码语言:javascript
复制
router.put('/', oneOf([
    check('name').exists().withMessage('Name is required'),
    check('student_id').exists().withMessage('Student id is required')
], 'Invalid request body'), (req, res, next) => {
    const errors = validationResult(req).formatWith(errorFormatter)
    if (
        !errors.isEmpty()
    ) {
        return res.status(422).json({errors: errors.mapped()})
    }
    else {
        res.send(req.user)
    }
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51525557

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档