javascript - 检查用户名或电话是否已存在(正面)
问题描述
我想知道我的前台表单上是否存在用户或电话,
我不等待答案,而是告诉我去做。
我使用 Yup + Formik 来满足我的所有需求。
在我使用 Sequelize 的后端,我设法显示用户名或电话是否存在:
passport.use(
'register',
new LocalStrategy(
{
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true,
session: false,
},
(req, username, password, done) => {
console.log(username);
console.log(req.body.phone)
try {
User.findOne({
where: {
[Op.or]: [
{
username,
},
{ phone: req.body.phone },
],
},
}).then(user => {
if (user != null) {
console.log('username or phone already taken');
return done(null, false, {
message: 'username or phone already taken',
});
}
bcrypt.hash(password, BCRYPT_SALT_ROUNDS).then(hashedPassword => {
User.create({
username,
password: hashedPassword,
phone: req.body.phone,
}).then(user => {
console.log('user created');
return done(null, user);
});
});
});
} catch (err) {
return done(err);
}
},
),
);
但是我很难理解这一点,我想我可以在我的 axios .catch 中获得这些信息?:
const onSubmit = async function onSubmit(values) {
axios({
method: 'POST',
url: 'http://localhost:4242/registerUser',
data: values,
headers: { 'Content-Type': 'application/json' },
})
.then(() => {
setModalOpen(true);
setUsername(nameRef.current.value);
setRedirect(true);
setCount(4);
})
.catch(function (error) {
});
};
return (
<div className="container-all-form">
<Formik
initialValues={initialValues}
validate={validate(getValidationSchema)}
onSubmit={onSubmit}
>
// my form
解决方案
您可以通过 2 种方式进行操作。一种是您可以在 catch 块中使用 error.response.message。
另一种方法是您可以在 then 函数中使用状态和记录错误,例如:
.then(res => res.json())
.then((response) => {
if (response.status === 200 || response.status === 201) {
setModalOpen(true);
setUsername(nameRef.current.value);
setRedirect(true);
setCount(4);
}
else {
console.log(response.message)
}
}).catch(err => {
console.log(err.response.message)
})
推荐阅读
- json - jq使用bash向现有文件添加行
- sql - 将逗号分隔的字符串拆分为行简化
- java - 我在 Joda-Time 的两个日期之间的时间错误
- jdbc - Kafka Connect - NoClassDefFoundError:无法初始化类 org.apache.calcite.jdbc.Driver
- java - tomcat 错误 404 - 源服务器没有找到目标资源的当前表示或不愿意透露存在的表示
- css - 移动 Safari,Css 动画在导航时冻结
- java - POJO + 属性文件声明的变量约束(使用 Lombok 和 Spring)
- python - python - 如何调整数据框的大小?熊猫
- angular - 将 typename 转换为输入打字稿
- .net - 隐式加载依赖 DLL