gpt4 book ai didi

javascript - NodeJs Express-Validator 自定义验证器不起作用

转载 作者:行者123 更新时间:2023-12-03 04:14:49 25 4
gpt4 key购买 nike

我使用express-validator customValidators来添加一些特定的验证器:

middlewares.js

module.exports = function (app) {
console.log('to be sure that Im called');
return function (request, response, next) {
app.use(expressValidator({
customValidators: {
checkObjectId: function(name) {
return /^[0-9a-fA-F]{24}$/.test(name);
}
}
}));
next();
}
};

route.js

const middleware = require(__path + '/middlewares');
module.exports = function (app, passport) {
router.use(baseUrl, middleware(app));
// some codes
router.put(baseUrl + '/invoice/:invoiceId', api.invoices.invoices.update);
}

发票.js

    update: (request, response) => {
// some codes
request.checkBody('from', 'invalid Supplier Id').checkObjectId();
// some codes
},

我的问题是 checkObjectId 无法识别,并且出现以下错误:

TypeError: request.checkBody(...).checkObjectId is not a function

最佳答案

您正在导出一个函数,该函数导出一个声明中间件的中间件。

这应该足够了:

// middlewares.js
module.exports = expressValidator({
customValidators: {
checkObjectId: function(name) {
return /^[0-9a-fA-F]{24}$/.test(name);
}
}
});

并使用:

const middleware = require(__path + '/middlewares');
module.exports = function (app, passport) {
router.use(baseUrl, middleware);
...
}

如果你确实想导出一个返回中间件的函数,你可以使用这个:

module.exports = function(app) {
return expressValidator({
customValidators: {
checkObjectId: function(name) {
return /^[0-9a-fA-F]{24}$/.test(name);
}
}
})
};

关于javascript - NodeJs Express-Validator 自定义验证器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44177514/

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