简体   繁体   English

React Axios 获取数据失败

[英]React Axios get data failed

I have a test application where I want to get data from fake API using Axios and pass to redux, but I get an error while getting data.我有一个测试应用程序,我想使用 Axios 从假 API 获取数据并传递给 redux,但在获取数据时出现错误。 How can I get the data correctly?如何正确获取数据?

I checked API via postman / get all data I get我通过 postman 检查了 API / 得到我得到的所有数据

SANDBOX 沙盒

API: Link API: 链接

Error: Unable to open 'createError.js': File not found (file:///sandbox/node_modules/axios/lib/core/createError.js).错误:无法打开“createError.js”:找不到文件 (file:///sandbox/node_modules/axios/lib/core/createError.js)。

Action.js动作.js

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

The problem is with your api url问题出在您的 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}"
};

Sand box is blocking the request as it is not https.沙盒正在阻止请求,因为它不是 https。 And your api doesnt have any certificate so your api will not support https而且您的 api 没有任何证书,因此您的 api 将不支持 https

But if you use that locally it will work but not with sandbox.但是,如果您在本地使用它,它将起作用,但不适用于沙箱。

Axios was blocked by codesandbox for this error and it should work locally, but at first you was handling the response improperly this is why you're not getting the payload , here is an explanation: 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);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM