); } return ComponentWithRouterProp;}// Yup 验证 schemaconst schema = yup.object({ username: yup.string().required(“用户名是必填项”), password: yup.string().required(“密码是必填项”), // 这里的必填项是客户端验证});function Login(props) { const [username, setUsername] = useState(“”); const [password, setPassword] = useState(“”); const { setIsLoggedIn } = useAuth(); const [submissionError, setSubmissionError] = useState(“”); // 新增:用于存储服务器端提交错误 const onUsernameChange = (event) => { setUsername(event.target.value); }; const onPasswordChange = (event) => { setPassword(event.target.value); }; const { handleSubmit, register, formState: { errors }, } = useForm({ resolver: yupResolver(schema), }); const formSubmit = async (data) => { // 将函数声明为 async setSubmissionError(“”); // 每次提交前清除之前的错误信息 try { const response = await fetch(“http://localhost:3001/login”, { method: “POST”, body: JSON.stringify({ username: data.username, password: data.password }), headers: { “Content-Type”: “application/json” }, }); if (response.status === 200) { // 登录成功 props.router.navigate(“/”); setIsLoggedIn(true); } else { // 处理服务器端错误 console.log(“登录失败,HTTP状态码:”, response.status); // 尝试解析JSON错误信息(如果服务器返回JSON格式的错误) if (response.headers.get(“Content-Type”)?.includes(“application/json”)) { const errorData = await response.json(); // 假设服务器返回的错误结构为 { error: “错误消息” } setSubmissionError(errorData.error || “登录失败,请检查您的用户名或密码。”); } else if (response.status === 400) { setSubmissionError(“请求参数错误,请检查输入。”); } else if (response.status === 401) { // 常见用于未授权或凭据不正确 setSubmissionError(“用户名或密码不正确。”); } else { setSubmissionError(“服务器内部错误,请稍后再试。”); } } } catch (error) { // 处理网络请求本身的错误(如断网) console.error(“登录请求出错:”, error); setSubmissionError(“网络连接失败,请检查您的网络。”); } }; return (
Log in
{/* 显示服务器端提交错误 */} {submissionError &&
{submissionError}
}
);}export default withRouter(Login);
微信扫一扫
支付宝扫一扫