【发布时间】:2021-12-04 02:17:30
【问题描述】:
我试图在后端显示一条错误消息,以防用户已经注册,但我没有得到我想要的结果。
后端代码:
module.exports.register = asyncHandler(async (req, res) => {
const { fullname, email, password } = req.body;
let user = await User.findOne({ email: email });
if (user) throw new Error("Email e/ou senha inválidos!");
user = await User.create({ fullname, email, password });
if (user) {
res.json({
_id: user._id,
name: user.fullname,
email: user.email,
token: tokenGenereator(user._id),
});
} else {
throw new Error("algo deu errado");
}
前端代码:
export const register = ({ fullname, email, password }) => {
return async (dispatch) => {
try {
const config = {
headers: {
"Content-type": "application/json",
},
};
const data = await axios.post(
"http://localhost:5000/api/register",
{
fullname,
email,
password,
},
config
);
dispatch(
uiActions.showNotificatoin({
variant: "success",
message: "Usuário cadastrado com sucesso!",
})
);
localStorage.setItem("userInfo", JSON.stringify(data));
} catch (error) {
console.log(error.response.data.error)
}
};
};
我需要做什么才能显示我抛出的消息?
【问题讨论】:
-
你能记录下数据吗?或尝试使其像这样:
const { data } = await...
标签: reactjs mongodb express axios backend