在 axios 发布请求后显示服务器身份验证响应时遇到了一个小问题。我正在尝试控制台日志服务器响应 errorMessage:“请在表单提交后填写所有必填字段。控制台一直显示“未定义”。在服务器端一切正常,网络选项卡显示正确响应。
const Login = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errors, setErrors] = useState("");
const { getLoggedIn } = useContext(AuthContext);
const history = useHistory();
async function login(e) {
e.preventDefault();
try {
const loginData = {
email,
password,
};
const res = await axios
.post("http://localhost:5000/auth/login", loginData)
.then((result) => {
console.log(result.data);
});
await getLoggedIn();
history.push("/player");
} catch (err) {
console.log(err.data);
}
}
return (
<div className="authWrapper">
<form className="box" onSubmit={login}>
<h1>LOGIN</h1>
<input
autoComplete="off"
className="input"
type="email"
placeholder="Email"
onChange={(e) => setEmail(e.target.value)}
value={email}
/>
<input
autoComplete="off"
className="input"
type="password"
placeholder="Password"
onChange={(e) => setPassword(e.target.value)}
value={password}
/>
<button className="submit" type="submit">
{`Log in${" "}`}
<FontAwesomeIcon icon={faArrowRight}></FontAwesomeIcon>
</button>
<Link to="/register">
<button className="changeForm">
{`Register${" "}`}
<FontAwesomeIcon icon={faSync}></FontAwesomeIcon>
</button>
</Link>
</form>
</div>
);
};
export default Login;
<div></div>;
答案 0 :(得分:2)
你们都在使用 async/await
等待响应并使用承诺链接行 .post().then().catch()
试试这个:
axios.post("http://localhost:5000/auth/login", loginData)
.then((result) => {
console.log(result.data);
await getLoggedIn();
history.push("/player");
})
.catch(err => {
console.log(err)
})
答案 1 :(得分:1)
因为你使用了promise,所以不会抛出异常,所以它不会命中你的try catch块。您需要在承诺上添加捕获:
const res = await axios
.post("http://localhost:5000/auth/login", loginData)
.then((result) => {
console.log(result.data);
}).catch((error) => {
console.error(error);
});
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
答案 2 :(得分:1)
只是在已经说过的内容中添加一些内容。如果您使用 await,则无需使用 .then() 来进行 Promise。 你可以这样试试:
const res = await axios.post("http://localhost:5000/auth/login", loginData)
console.log(res.data);
您将等待服务器的响应。获得后,它将存储在您创建的 res 常量中。 此外,您需要在每次 try 编写后添加一个 catch 块。