2

我在我的项目中遇到了 axios 的一个大问题。我使用 axios 在getServerSideProps. 但它是否显示“请求失败,状态码为 404”,同时我还使用 axiosuseEffect从 api 获取数据。

export async function getServerSideProps() {
  try {
    const ApiUrl = apiBaseUrl + "/api/my-url";
    const homeData = await axios
      .get(ApiUrl)
      .then((response) => {
        return response.data;
      })
      .catch((error) => {
        return error.message;
      });

    return {
      props: {
        homeData: homeData, // its is return Request failed with status code 404
        error: false,
        ApiUrl: ApiUrl,
      },
    };
  } catch (e) {
    return {
      props: {
        error: true,
        homeData: null,
        message: e.message,
      },
    };
  }
}

通过我 cna 无法从getServerSideProps我使用的数据中获取数据useEffect

useEffect(() => {
  if (typeof props.homeData === "string") {
    console.log(props); // it is showing error 'Request failed with status code 404'
  } else if (props.homeData) {
    console.log(props.homeData);
    // setData(props.homeData);
  } else {
    axios
      .get(apiBaseUrl + "/api/my-url")
      .then((response) => {
        seteData(response.data);
      })
      .catch((error) => {
        console.log(error);
      });
  }
}, [props]);
4

0 回答 0