gpt4 book ai didi

javascript - 使用express-validator作为Express中间件不起作用

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

我正在使用 npm 模块[express-validator][1] 来验证我的querybody 参数。与在express中一样,我们可以将函数列表作为中间件传递,我创建了一个单独的文件作为验证器。这是我的验证器代码..

creditcard.validator.js

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

exports.post_credit_check = [
function(req,res,next) {
body('firstName')
.exists()
.isAlphanumeric().withMessage('firstName should be alpanumeric')
.isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
.trim();
var errorValidation = validationResult(req);
if ( errorValidation ) {
return res.status(500).json({
title: 'an error occured',
error: errorValidation
});
}
next()
},

function(req,res,next) {
body('lastName')
.exists()
.isAlphanumeric().withMessage('lastName should be alpanumeric')
.isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
.trim();
var errorValidation = validationResult(req);
if ( errorValidation ) {
return res.status(500).json({
title: 'an error occured',
error: errorValidation
});
}
next()
}
];

这是我传递中间件验证器数组的 route 文件

var express = require('express');
var router = express.Router();
var Creditcard = require('../models/creditcard.model');
const { validationResult } = require('express-validator/check');
var validate = require('../models/creditcard.validate');

router.post('/creditcarddetails', validate.post_credit_check , function(req, res, next) {
.................
}

虽然我在 validate.post_credit_check 中传递了所有中间件函数,但它没有验证正文也没有给出错误。

最佳答案

我认为 check 方法已经是一个中间件了,不需要在另一个中间件中调用它,你的代码应该是:

exports.post_credit_check =  [
body('firstName')
.exists()
.isAlphanumeric().withMessage('firstName should be alpanumeric')
.isLength({min: 1 , max: 50}).withMessage('firstName should not be empty, should be more than one and less than 50 character')
.trim(),
function(req,res,next) {
var errorValidation = validationResult(req);
if ( errorValidation ) {
return res.status(500).json({
title: 'an error occured',
error: errorValidation
});
}
next()
},
body('lastName')
.exists()
.isAlphanumeric().withMessage('lastName should be alpanumeric')
.isLength({min: 1 , max: 50}).withMessage('lastName should not be empty, should be more than one and less than 50 character')
.trim(),
function(req,res,next) {

var errorValidation = validationResult(req);
if ( errorValidation ) {
return res.status(500).json({
title: 'an error occured',
error: errorValidation
});
}
next()
}
];

关于javascript - 使用express-validator作为Express中间件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47311713/

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