javascript - 验证器在反应中向表单寄存器抛出错误请求
问题描述
我正在使用 redux 制作一个反应应用程序,用户需要注册和登录并需要填写表格。我已经使用 isempty 实现了表单验证。但是,当我使用验证运行代码时,它会返回错误的请求 {} 错误。无需验证即可正常工作。
这是我的验证文件:
注册.js
const Validator = require('validator');
const isEmpty = require('./isempty');
module.exports = function validateRegisterInput(data){
let errors ={};
if (!Validator.isLength(data.name, {min: 3, max: 30})){
errors.name = 'Name must be between 3 and 30 characters';
}
if (isEmpty(data.name)){
errors.name = 'Name is required';
}
if (!Validator.isEmail(data.email)){
errors.email = 'Email is invalid';
}
if (isEmpty(data.email)){
errors.email = 'Email is required';
}
if (!Validator.isLength(data.password, {min: 6, max: 30})){
errors.password = 'Password must be between 6 and 30 characters';
}
if (isEmpty(data.password)){
errors.password = 'Password is required';
}
if (isEmpty(data.password2)){
errors.password2 = 'Confirm Password is required';
}
if (!Validator.equals(data.password, data.password2)){
errors.password2 = 'Passwords must match';
}
return {
errors,
isValid: isEmpty(errors)
}
}
是空的 Js :
const isEmpty = value =>
value === undefined ||
value === null ||
(typeof value === "Object" && Object.keys(value).length === 0) ||
(typeof value === "string" && value.trim().length === 0)
module.exports = isEmpty;
API调用:
_route.post('/register',(req,res) => {
const {errors, isValid} = validateRegisterInput(req.body);
if(!isValid){
return res.status(400).json(errors);
}
User.findOne({email: req.body.email})
.then(user => {
if (user){
return res.status(400).json({email: 'Email already exists'});
} else {
const avatar = gravatar.url(req.body.email, {
s: '200',
r: 'pg',
d: 'mm'
});
const newUser = new User({
name: req.body.name,
lastname: req.body.lastname,
email: req.body.email,
password: req.body.password,
avatar
});
bcrypt.genSalt(10, (err, salt) => {
if(err) throw err;
bcrypt.hash(req.body.password, salt, (err, hash) => {
if (err) throw err;
newUser.password = hash;
newUser.save()
.then(user => res.json(user))
.catch(err => console.log(err))
logger.info(`User successfully created id: email:`)
});
});
}
})
.catch(err => console.log(err));
});
可能是什么问题?
解决方案
推荐阅读
- vue.js - 如何控制套接字连接请求何时从客户端发送到后端?
- xcode - 无法从 .xcconfig 设置捆绑标识符以进行自动签名
- c - 我是否正确地在函数中实现指针?
- kubernetes - Kubernetes Secret 是如何挂载的?
- android - 启动一个fragment就是重启父fragment
- python-3.x - Snakemake - 如何使用文件的每一行作为输入?
- python - 有多个存储桶时如何从s3指定存储桶路径
- c# - 在 Azure Functions 中运行时 Environment.Exit 有什么作用?
- python - 无法在 matplotlib 图中获取正确的文本边界坐标
- android - 如何以编程方式添加另一种语言