当表单为空时,按Login按钮将打开该页面。我想让他犯个错误。如果它与服务器不兼容,我已经收到一个错误。我该如何解决这个问题?
const login = (e) => {
e.preventDefault();
axiox.post("http://localhost:2000/api/auth/login", {
email,
password
}).then((response) => {
console.log("response", response)
localStorage.setItem("login", JSON.stringify({
userLogin: true,
token: response.data.access_token,
}));
setError("");
setEmail("");
setPassword("");
history.push("schools");
})
.catch((error) => setError(error.response.data.message));
};发布于 2021-09-25 12:13:14
使用此命令验证表单
const login = (e) => {
e.preventDefault();
if(!email || !password){
//send error message to user
}else{
// make request to api
}
};发布于 2021-09-25 12:25:24
一种简单而有效的方法是在客户端检查任何错误,即如果表单为空,则不应该进行API调用。对表单或函数进行验证以检查值是否为null就足够了。
您可以在表单上添加更多的验证,但是,某些业务授权的验证可以在服务器端完成。
const login = (e) => {
e.preventDefault();
// make request to api
if(!email && !password) {
//here make the API call to authenticate a user
}
};查看this链接以获取更多详细信息,以及如何在React表单中添加验证。
发布于 2021-09-25 12:37:13
我认为当他们还没有填写表单时,您希望表单回复一条错误消息。这里:
const login = (e) => {
e.preventDefault();
if(!email || !password){
//Send the error message, like alert('Either the Email or Password is empty!')
}else{
//The code to execute when both Email and Password are filled.
}
};https://stackoverflow.com/questions/69325955
复制相似问题