在打字稿上设置类型错误尝试捕获,除了 error.message

问题描述 投票:0回答:1

我创建了一个从服务器端发送的自定义错误消息,当然我不只是使用

错误消息

获取消息。所以我用

错误.响应.数据

获取消息并收到如下代码所示的错误。

const handleLogin = async (formData: FormData) => {
  const email = formData.get("email");
  const password = formData.get("password");

  axios
    .get("http://localhost:8000/sanctum/csrf-cookie")
    .then(async () => {
      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: unknown) {
        console.log((error as Error).response.data); // Property 'response' does not exist on type 'Error'.
      }
    })
    .catch((error) => {
      console.log(`Error: ${error.message}`);
    });
};

请帮我解决这个问题,我真的很感激

reactjs typescript next.js axios
1个回答
0
投票

您遇到此问题是因为 TypeScript 中默认的

Error
类型没有
response
属性。使用 Axios 时,错误通常是
AxiosError
类型,其中包括
response

    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}`);
  }
};
© www.soinside.com 2019 - 2024. All rights reserved.