如何在发出 post 请求后使用 Vue 向用户显示一系列从 Express 到用户的错误.js



我正在尝试使用Express,Vue.js和MongoDB创建一个基本的注册/注册Web应用程序。

我已经编写了一些后端验证,例如检查所有字段是否填写以及密码匹配等......然后在用户验证失败时将错误消息字符串推送到数组中。

如果用户尝试在前端注册并且验证的某些部分失败,则不会将用户插入到数据库中,而是显示有关原因以及我遇到问题的消息。

router.post("/register", (req, res) => {
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
const password2 = req.body.password2;
let errors = [];
// check required fields
if (!name || !email || !password || !password2) {
errors.push({ msg: "please fill in all fields" });
}
// check for errors
if (password !== password2) {
errors.push({ msg: "Passwords do not match" });
}
// password validation
if (password.length < 6) {
errors.push({ msg: "Password to short" });
}
if (errors.length > 0) {
// if there are errors redirect
res.redirect("/");
console.log(errors);
} else {
// res.send("pass");
// check if the user already exists:
User.findOne({ email: email }).then(user => {
if (user) {
// User exists
// if you have found one user
// then user exists and send to home page
errors.push({ msg: "Email is already registered" });
res.redirect("/");
console.log(errors);
} else {
// create new user by using the keyword 'new'
//  name is equal to const name = req.body.name; etc...
const newUser = new User({
name: name,
email: email,
password: password
});
console.log(newUser + " hi new user");
// Hash Password before insert into db
bcrypt.genSalt(10, (err, salt) =>
bcrypt.hash(newUser.password, salt, (err, hash) => {
if (err) throw err;
// set PS to hashed PS
newUser.password = hash;
// save user
// insert into db then redirect to login
newUser
.save()
.then(user => {
res.redirect("/login");
})
.catch(err => {
console.log(err);
});
})
);
}
});
}
});

Vue:

name: "RegisterForm",
// data is a function that
//  returns an object
data: () => ({
errorMessage: "",
user: {
name: "",
email: "",
password: "",
password2: ""
}
}),
// watch allows you to run a function
// any time data changes
watch: {
user: {
handler() {
this.errorMessage;
},
// deep means anytime data changes this watch will run
deep: true
}
},
methods: {
register() {  
// clear error message on register
this.errorMessage = "";
// use keyword 'this' to refer to the current object 'methods'
if (this.validUser()) {
// send data to server
axios({
method: "post",
url: "http://localhost:4000/register",
data: {
name: this.user.name,
email: this.user.email,
password: this.user.password,
password2: this.user.password2
}
})
.then(response => {
console.error(response)
})
.catch(error => {
console.error(error)
});
}
},
validUser() {
// if (this.user.password !== this.user.password2) {
//   this.errorMessage = "Passwords must match";
//   return false;
// } else {
return true;
//   }
// }
}
}
};

有一些前端验证可以工作(通过这样做.errorMessage ="密码必须匹配或某些错误;)并显示一条消息,但我需要显示来自"let errors = []"的错误

目前,当输入无效数据(例如两个不匹配的密码(时,我目前在控制台中收到"参考错误:未定义错误"错误。

使用快速闪存消息在重定向时保存它们。此插件还公开了一个局部变量来呈现这些消息。请参阅文档。

相关内容

最新更新