簡體   English   中英

如果正文是單個json數組,如何驗證請求正文?

[英]How to validate the request body if the body is a single json array?

我正在嘗試使用express-validator請求的主體express-validator主體是單個數組,所以我沒有字段名稱。

我正在使用express-validatorexpress版本4的新API。

身體看起來像這樣:

["item1","item2"]

我的代碼:

app.post('/mars/:Id/Id', [
    check('id')
        .isLength({  max: 10 })

    .body() //try many ways to get the body. most examples i found were for the old api
    .custom((item) => Array.isArray(item))
],
    (req, res, next) => {           
       const data: string = matchedData(req); //using this method to only pass validated data to the business layer
       return controller.mars(data); //id goes in data.id. i expect there should be an data.body once the body is validated too.
    }

我如何驗證身體?

我按照文檔中的說明進行了操作,這是代碼:只需在代碼中的expressValidator參考之后聲明自定義驗證器即可。

app.use(expressValidator());
app.use(expressValidator({
    customValidators: {
        isArray: function(value) {
            return Array.isArray(value);
        }
    }
}));

之后,您可以像這樣檢查有效性:

req.checkBody('title', 'title é obrigatório').notEmpty();
req.checkBody('media','media must be an array').isArray();

我在項目中使用的是3.2.0版,因此我可以實現此行為。 這是我的請求正文的示例:Exports.validateAddArrayItem = function(req,res,next){{標題:'foo',媒體:[1,2,3]}

另外,如果您不想更改響應,我曾經做過這樣的驗證:

if (req.body.constructor === Array) {
        req.body[0].employee_fk = tk.employee_id;
    }
    req.assert('item', 'The body from request must be an array').isArray();

    var errors = req.validationErrors();
    if (errors) {
        var response = { errors: [] };
        errors.forEach(function(err) {
            response.errors.push(err.msg);
        });
        return res.status(400).json(response);
    }
    return next();
};

這是我的請求正文的示例:

[{
employeefk: 1,
item: 4
}]

如果您使用的是ajax,請嘗試將數組放入對象中,如下所示:

$.ajax({
    type: "POST",
    url: url,
    data: { arr: ["item1", "item2"] },
    success: function (data) {
        // process data here
    }
});

現在,您可以使用arr標識符應用驗證規則:

const { check, body, validationResult } = require('express-validator/check');

...

app.post('/mars/:Id/Id', [
    check('chatId').isLength({  max: 10 }),
    body('arr').custom((item) => Array.isArray(item))
], (req, res, next) => {           
       const data: string = matchedData(req); 
       return controller.mars(data); 
});

暫無
暫無

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

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