【问题标题】:Are these errors a result of the Axios API call?这些错误是 Axios API 调用的结果吗?
【发布时间】:2022-01-12 19:05:56
【问题描述】:

我正在开发一个后端 API,调用该 API 的 React 前端随机获得一个 Network ErrorCannot read properties of undefined (reading 'data')。我一直无法重现这种行为。它正在前端的日志中报告,并且它没有显示在后端的日志中,据我所知,请求甚至没有命中 API。前端使用 Axios 进行 API 调用。下面是出现这些错误的两个调用的示例。此代码中的任何内容都可能导致这些错误?

const params = `email=${this.queryParams.email}`;

const response = await axiosStore.axiosApi.get(`/data?${params}`).catch(error => {
    console.error(error);
});
const values = await response.data;

this.setValues(values);
const response = await axiosStore.axiosApi.post(`/data`, { data: mappedChanges }).catch(error => {
    if (error && error.response && error.response.data && error.response.data.errors) {
        const { errors } = error.response.data;
        const message = Object.keys(errors)
            .map(x => errors[x])
            .join(', ');
        throw new Error(message);
    } else {
        throw new Error('Something went wrong');
    }
});
newObject = response.data;

【问题讨论】:

    标签: reactjs api axios frontend


    【解决方案1】:

    好吧,我猜是因为你混合了 await 和 catch 可能会附加错误。如果您的通话中有错误。你抓住它然后响应对象可能是未定义的。 然后,当您尝试从响应中获取数据时,您将收到此错误。 而且我不确定您是否需要在 response.data 上调用 await。你确定这是一个承诺? 如果我是你,我会将调用包装成 try catch 以使调试更容易

    
    const getStuff1 = async () => {
      const params = `email=${this.queryParams.email}`;
      try {
        const response = await axiosStore.axiosApi.get(`/data? ${params}`);
        const values = response.data;
        this.setValues(values);
      } catch(error) {
        console.error(error);
      }    
    };
    
    const getStuff2 = async () => {
      try {
        const response = await axiosStore.axiosApi.post(`/data`,
         { data: mappedChanges }
        );
        newObject = response.data;
      } catch(error) {
        if (error?.response?.data?.errors) {
          const { errors } = error.response.data;
          const message = Object.keys(errors)
                .map(x => errors[x])
                .join(', ');
            // Do something with error
        } else {
            // Do something with error
        }
      }
    
    };
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-11
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 2021-01-05
      • 2015-09-18
      • 2011-03-09
      • 1970-01-01
      相关资源
      最近更新 更多