【问题标题】:React Axios get data failedReact Axios 获取数据失败
【发布时间】:2020-12-05 20:25:37
【问题描述】:

我有一个测试应用程序,我想使用 Axios 从虚假 API 获取数据并传递给 redux,但在获取数据时出现错误。如何正确获取数据?

我通过邮递员检查 API / 获取我得到的所有数据

SANDBOX

API: Link

错误: 无法打开“createError.js”:找不到文件 (file:///sandbox/node_modules/axios/lib/core/createError.js)。

Action.js

export const getDataTablePayload = () => {
  const payload = axios.get(API.bigData).then((response) => response.data);
  console.log(payload);
};

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    问题在于你的 api url

    export const API = {
      smallData:
        "http://www.filltext.com/?rows=32&id={number|1000}&firstName={firstName}&lastName={lastName}&email={email}&phone={phone|(xxx)xxx-xx-xx}&address={addressObject}&description={lorem|32}",
      bigData:
        "http://www.filltext.com/?rows=1000&id={number|1000}&firstName={firstName}&delay=3&lastName={lastName}&email={email}&phone={phone|(xxx)xxx-xx-xx}&address={addressObject}&description={lorem|32}"
    };
    

    沙盒正在阻止请求,因为它不是 https。而且您的 api 没有任何证书,因此您的 api 将不支持 https

    但如果你在本地使用它,它会工作,但不适用于沙盒。

    【讨论】:

      【解决方案2】:

      Axios 因此错误被代码和框阻止,它应该在本地工作,但起初您处理响应不正确,这就是您没有收到 payload 的原因,这里有一个解释:

      export const getDataTablePayload = () => {
        const payload = axios.get(API.bigData).then((response) => response.data); // this is async code
        // the console will run before the data will be fetched so you have two solution ?
        console.log(payload);
      };
      
      1.
      export const getDataTablePayload = () => {
        axios
          .get(API.bigData)
          .then((response) => response.data)
          .then((data) => {
            // do your work here
          });
      };
      
      2.
      export const getDataTablePayload = async () => {
        const response = await axios.get(API.bigData)
        // here await will wait until the data will be fetched
        console.log('payload', response.data);
      };
      

      【讨论】:

      • 你在本地检查了吗?
      • 对不起我的错误,我会做异步尝试捕获并使用 react thunk for distpach
      • 是的,应该没问题!
      猜你喜欢
      • 2022-01-04
      • 2020-06-19
      • 2021-07-27
      • 2021-02-08
      • 2021-09-23
      • 2017-09-05
      • 2020-08-21
      • 2021-07-09
      • 2020-06-10
      相关资源
      最近更新 更多