【发布时间】:2021-12-30 11:09:45
【问题描述】:
基本上我有我的 AuthContext,还有我的 reducer、actions 和 apicalls。
AuthReducer:
case "LOGIN_FAILURE":
return {
user: null,
isFetching: false,
error: true,
};
授权操作:
export const loginFailure = () => ({
type:"LOGIN_FAILURE",
});
ApiCalls:
export const login = async (user, dispatch) => {
dispatch(loginStart());
try {
const res = await axios.post("/auth/login", user);
dispatch(loginSuccess(res.data));
} catch (err) {
dispatch(loginFailure());
}
};
以及我的 api 中的实际调用:
router.post("/login", async (req, res) => {
try {
const user = await User.findOne({ email: req.body.email });
!user && res.status(401).json("Wrong password or username!");
const bytes = CryptoJS.AES.decrypt(user.password, process.env.SECRET_KEY);
const originalPassword = bytes.toString(CryptoJS.enc.Utf8);
originalPassword !== req.body.password &&
res.status(401).json("Wrong password or username!");
const accessToken = jwt.sign(
{ id: user._id, isAdmin: user.isAdmin },
process.env.SECRET_KEY,
{ expiresIn: "5d" }
);
const { password, ...info } = user._doc;
res.status(200).json({ ...info, accessToken });
} catch (err) {
res.status(500).json();
}
});
在我的组件中:
const handleLogin = (e) => {
if(email.match(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g)){
login({email, password}, dispatch);
e.preventDefault();
history.push("/");
}
};
一切都很好。现在,当我输入错误的登录凭据时,显然没有任何反应。在 Network -> Response 下的 chrome 控制台中,我得到了“错误的用户名或密码”。但是如何获取 401 响应以将其显示在我的组件中,这样如果我输入了错误的登录凭据,我就可以在我的登录按钮上显示它。
【问题讨论】:
标签: javascript reactjs mongodb