gpt4 book ai didi

javascript - 检查用户名或电话是否已存在(正面)

转载 作者:行者123 更新时间:2023-12-01 00:32:35 26 4
gpt4 key购买 nike

我想知道我的前台表单上是否存在用户或电话,

我不等待答案,而是等待告诉我去做的事情。

我使用 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

最佳答案

您可以通过两种方式做到这一点。一是您可以在 catch block 中使用 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)
})

关于javascript - 检查用户名或电话是否已存在(正面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58394872/

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