我有代码(如下),一位开发人员对我说我必须验证我的请求:
router.post('/dashboard', passport.authenticate('jwt', { session: false }),
(req, res) => {
try {
let newPost = new Post({
category: req.body.category,
title: req.body.title,
photo: req.body.photo,
text: req.body.text,
author: req.body.author,
date: req.body.date
});
Post.addPost(newPost, (err, user) => {
if (err) {
res.json({success: false, msg: `Post has not been added. ${err}`})
} else {
res.json({success: true, msg: 'Post was added.'})
}
})
} catch (err) {
const error = (res, error) => {
res.status(500).json({
success: false,
message: error.message ? error.message : error
}) …Run Code Online (Sandbox Code Playgroud) express-validator,如何使一个字段仅在另一个字段存在时才为必填?
const validateUpdateStore = () => {
return [
body('logo').optional().isURL().withMessage('invalid url'),
body('email')
.optional()
.isEmail()
.withMessage('email is invalid')
.trim()
.escape(),
body('phone').optional().isInt().withMessage('integers only!'),
body('account_number').optional().isInt().withMessage('integers only!'),
body('bank_code').optional().isInt().withMessage('integers only!'),
];
};
Run Code Online (Sandbox Code Playgroud)
我想bank_code仅在account_number提供该字段时才将其设置为必填字段,反之亦然
我正在使用express-validator进行验证.我使用mongoose作为数据库,它也内置了验证.我想知道我应该使用哪一个?
我还想知道express-validator中的验证是否是并行的.以此代码为例:
req.checkBody('email', 'Invalid email').notEmpty().isEmail().isUnique();
req.checkBody('password', 'Invalid possword').notEmpty().len(8, 30);
req.checkBody('first_name', 'Invalid first_name').notEmpty().isAlpha();
req.checkBody('last_name', 'Invalid last_name').notEmpty().isAlpha();
req.checkBody('dateofbirth', 'Invalid dateofbirth').notEmpty.isDate();
Run Code Online (Sandbox Code Playgroud)
isUnique()是一种自定义验证方法,用于检查电子邮件是否尚未注册,它会向数据库查询以进行验证.虽然上面的代码中没有提到,但我还有其他一些帖子请求,我需要验证多个字段,在这些字段中将对每个字段进行数据库查询.
所以我想知道是否有可能并行运行上述每个检查方法,因为这会使它更快,并且我也会更像节点.我显然想使用一个模块来并行运行这些async.我还想知道这些检查方法是否已经并行运行了?
请帮我解决这个问题?提前致谢.
我通过websockets使用Sails.js + Passport.js身份验证来通过websockets绑定passport.js方法(使用sockets.io),但我应该如何添加express-validator方法以确保所有请求都有来自它的方法
我正在express-validator我的 Express 应用程序中使用,并且我试图阻止在 POST 请求上指定其他字段。这是因为我将 的值传递req.body给 ORM 以插入到数据库中,并且我希望避免在添加验证器的同时在插入的对象和请求正文之间显式映射。
这可能吗?我似乎在文档中找不到它。使用 JSON Schema 你可以这样做additionalProperties: false
我想使用 Express-Validator 验证请求对象。假设我有两个路由,一个GET /users/:id (fetchUserById) 和POST /users (createUser) 路由
this.router = express.Router();
this.router.route('/').post(this.userRequestValidator.createUser, this.userController.createUser);
this.router.route('/:id').get(this.userRequestValidator.fetchUserById, this.userController.fetchUserById);
Run Code Online (Sandbox Code Playgroud)
如您所见,我在调用控制器逻辑之前调用了验证中间件。首先,我创建了一个基本验证器来处理验证错误并在出现问题时返回 HTTP 400。
export abstract class RequestValidator {
protected validate = async (request: Request, response: Response, next: NextFunction): Promise<void> => {
const errors: Result<ValidationError> = validationResult(request);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
} else {
next();
}
};
}
Run Code Online (Sandbox Code Playgroud)
我的验证器函数userRequestValidator.createUser和userRequestValidator.fetchUserById只需要扩展 RequestValidator 并实现验证
export class UserRequestValidator extends RequestValidator {
public createUser = [
body('username')
.isString()
.exists(),
body('password') …Run Code Online (Sandbox Code Playgroud) 因此,我对此进行了大量研究,但遇到了一些问题。
router.post('/register', async (req, res) => {
const newUser = await usersDb();
// Define the user
const email = req.body.email;
const username = req.body.username;
const password = req.body.password;
const confirmPassword = req.body.confirmPassword;
// Start user already exist check
let userNameCheck = await newUser.findOne({ 'username': username});
req.check('email', 'Email is not valid.').isEmail()
.custom(async value => {
let emailCheck = await newUser.findOne({ 'email': value });
console.log(emailCheck);
console.log('Hmmm')
if (emailCheck !== null) {
return true;
} else {
return false;
}
}).withMessage('Email is already …Run Code Online (Sandbox Code Playgroud) 我正在提交带有图像的表格。使用下面的代码。
router.post("/", upload.upload('image').single('categoryLogo'), categoryRules.categoryCreationRules(), validate, categoryController.createCategory);
Run Code Online (Sandbox Code Playgroud)
它工作正常,但是需要进行一些验证,然后静态图像才会保存在磁盘中。所以我尝试的是:
router.post("/", categoryRules.categoryCreationRules(), validate,upload.upload('image').single('categoryLogo'), categoryController.createCategory);
Run Code Online (Sandbox Code Playgroud)
但在这个快速验证器中得到空白主体,因此它经常抛出验证错误。我应该做什么,我在谷歌上搜索,但没有找到任何有用的信息,我是节点中的新手。
规则代码:
const categoryCreationRules = () => {
return [
check('name')
.isLength({ min: 1 })
.trim()
.withMessage("Category name is required."),
check('name').custom((name)=>{
return CategoryModel.findOne({name: name}).collation({locale:'en',strength: 2})
.then(category=>{
if(category){
return Promise.reject(category.name+" category already exsist.");
}
})
}),
check('name')
.isLength({max: 100})
.trim()
.withMessage("Category name should not exceed more then 100 characters."),
check('description')
.isLength({max: 255})
.trim()
.withMessage("Category description should not exceed more then 255 characters.")
];
}
Run Code Online (Sandbox Code Playgroud) 我遇到了快速验证器使用两个键验证对象的问题。我的方法如下。
check('contact.code')
.trim()
.isNumeric()
.withMessage('Country code must be numeric.')
.bail()
.isLength({min: 1, max: 4})
.withMessage('Invalid country code.')
.bail(),
check('contact.number')
.trim()
.isNumeric()
.withMessage('Phone number must be numeric.')
.bail()
.isLength({max: 10, min: 10})
.withMessage('Phone number must be 10 digits long.')
.bail(),
Run Code Online (Sandbox Code Playgroud)
在req.body中,我将我的联系人发送为,
contact: {"code": "91", "number":"9087654321"}
但我收到错误:
{
"errors": [
{
"value": "",
"msg": "Country code must be numeric.",
"param": "contact.code",
"location": "body"
},
{
"value": "",
"msg": "Phone number must be numeric.",
"param": "contact.number",
"location": "body"
}
]
} …Run Code Online (Sandbox Code Playgroud) node.js ×10
express ×8
javascript ×4
validation ×2
arrays ×1
asynchronous ×1
joi ×1
multer ×1
request ×1
sails.js ×1
socket.io ×1
typescript ×1