簡體   English   中英

主體錯誤不觸發快速驗證器

[英]Body errors not triggering express-validator

盡管執行了所有日志記錄標志,但我創建的代碼中未觸發驗證中間件代碼。

const { check, validationResult } = require("express-validator");

module.exports = {
    validateUsers(req, res, next) {
        if (req.method === "POST") {
            console.log(req.body.email);
            check(["email", "Must consist only of letters."]).isEmail();
        }

        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.json(errors);
        }  else {
            return next();
        }
    }
}

我試過使用check發送reqreq.body ,以及將body與這兩個選項一起使用。 控制台日志顯示提供的非電子郵件字符串,並且我嘗試了其他字段和其他(失敗)值。

誰能指出我有用的方向? 我用過舊版本的checkBody ,但我堅持使用這些。 我一直在關注app.js ,但現在沒有未注釋的代碼。

check返回一個中間件,但您沒有使用它並將所需的參數傳遞給它。

const { check, validationResult } = require("express-validator");

module.exports = {
    validateUsers(req, res, next) {
        if (req.method === "POST") {
            console.log(req.body.email);
            const middleware = check(["email", "Must consist only of letters."]).isEmail();
            middleware(req, res, next)
           
        }

        const errors = validationResult(req);

        if (!errors.isEmpty()) {
            return res.json(errors);
        }  else {
            return next();
        }
    }
}

我建議雖然這有點不符合人體工程學。 它甚至可能不起作用,因為從check返回的中間件可能會調用 next,然后您的代碼就沒有意義了。 它旨在以不同的方式使用。 這樣做可能會更干凈:

const { body, validationResult } = require("express-validator");

module.exports = {
    validateUsers: [
            body(["email", "Must consist only of letters."]).isEmail(),
            (req, res, next) => {
                const errors = validationResult(req);

                if (!errors.isEmpty()) {
                    return res.json(errors);
                }  else {
                    return next();
                }
            }
        ]
}

然后像這樣使用:

app.post('/thing', validateUsers, (req, res, next) => {
   // you'd get here only if there were no issues
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM