javascript - NextJS - 你可以在有条件的情况下使用来自 api 的返回吗?
问题描述
我有一个更改密码功能,可以点击这个 api 进行验证,如果当前密码不正确,我想显示一个错误。
关于如何进行此操作的任何方向,或者如果我正在做的事情没有意义,请指出我正确的方向,如果会如此友好,将不胜感激!
case "PUT":
try {
const validContact = await Contact.findOne({ _id: req.body.id });
const valid = bcrypt.compareSync(
req.body.currentPassword,
validContact.password
);
if (valid) {
const hashedPassword = bcrypt.hashSync(
req.body.newPassword,
bcrypt.genSaltSync()
);
const contact = await Contact.findOneAndUpdate(
{ _id: req.body.id },
{ password: hashedPassword },
{ new: true }
);
res.status(200).json({ success: true, data: contact });
}
res.status(400).json({ success: false });
} catch (error) {
res.status(400).json({ success: false });
}
break;
这是在提交表单时调用 API 的函数
const submitNewPassword = (submitNewPasswordForm, resetForm) => {
submitNewPasswordForm(); // <-- I want to put this in a conditional
resetForm();
setOpenPasswordPopup(false);
setNotify({
isOpen: true,
message: "Password updated successfully",
type: "success",
});
};
编辑: submitNewPassword 功能
const submitNewPasswordForm = async () => {
try {
const res = await fetch(`${process.env.APP_DOMAIN}/api/${apiRoute}`, {
method: "PUT",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(values),
});
router.push(`${process.env.APP_DOMAIN}/`);
} catch (error) {
console.log(error);
}
};
解决方案
你submitNewPasswordForm
现在没有返回任何东西(嗯,它确实,但它只是一个空的 Promise)。为了能够检查它是否是一个好的请求,您需要从中返回一些东西。例子:
const submitNewPasswordForm = async () => {
try {
const res = await fetch(`${process.env.APP_DOMAIN}/api/${apiRoute}`, {
method: "PUT",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(values),
});
// this check is also necessary; 400 isn't an exception that would get caught
if (!res.ok) {
throw new Error(res.statusText)
}
router.push(`${process.env.APP_DOMAIN}/`);
return true;
} catch (error) {
console.log(error);
// you could also re-throw the error, or return something else
return false;
}
};
因为它是一个异步函数,它返回一个 Promise,所以你需要用 a 来获取返回值.then
:
const submitNewPassword = (submitNewPasswordForm, resetForm) => {
submitNewPasswordForm()
.then((ok) => {
if (!ok) {
// show error
} else {
resetForm();
setOpenPasswordPopup(false);
setNotify({
isOpen: true,
message: "Password updated successfully",
type: "success",
});
}
})
};
如果你在第一个函数中重新抛出错误,你可以.catch
这样做而不是检查一个ok
值。如果您愿意,也可以将第二个函数async
设为函数。例子:
const submitNewPassword = async (submitNewPasswordForm, resetForm) => {
try {
submitNewPasswordForm()
// rest of the code
} catch (err) {
// show error
}
}
无论您采用哪种方式,您都必须从函数中返回一些内容才能知道它是否成功。
推荐阅读
- c++ - 编写 `&str_send[0] = &str_recv[c * 6];` 时,C++ 表达式不可赋值
- ios - Firebase中不存在确定表的方法
- html5-video - 如何计算 Chrome 和 Safari 中的真实视频帧率?
- sql - 排序记录比较多个表的总和
- c++ - OpenGL 忽略四边形并将它们变成三角形
- python - How to unnest (explode) a column in a pandas DataFrame, into multiple rows
- c - x86-64 结构中的数据对齐
- python - 二维函数不返回值数组?
- git - Git存储库在新存储库上显示多个贡献者?
- installation - 在 Visual Studio 中创建设置/安装项目