您遇到此问题是因为默认
Error
TypeScript中的类型没有
response
财产。使用Axios时,错误通常为
AxiosError
类型,包括
响应
.
import axios, { AxiosError } from "axios";
const handleLogin = async (formData: FormData) => {
const email = formData.get("email");
const password = formData.get("password");
try {
await axios.get("http://localhost:8000/sanctum/csrf-cookie");
try {
const response = await axios.post(
"http://localhost:8000/api/login",
{ email, password },
{
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
}
);
console.log(response.data);
} catch (error) {
if (axios.isAxiosError(error)) {
console.error(error.response?.data); // Use optional chaining to avoid undefined errors
} else {
console.error("An unexpected error occurred:", error);
}
}
} catch (error) {
console.error(`Error during CSRF request: ${error.message}`);
}
};