[英]React Axios get data failed
我有一個測試應用程序,我想使用 Axios 從假 API 獲取數據並傳遞給 redux,但在獲取數據時出現錯誤。 如何正確獲取數據?
我通過 postman 檢查了 API / 得到我得到的所有數據
API: 鏈接
錯誤:無法打開“createError.js”:找不到文件 (file:///sandbox/node_modules/axios/lib/core/createError.js)。
動作.js
export const getDataTablePayload = () => {
const payload = axios.get(API.bigData).then((response) => response.data);
console.log(payload);
};
問題出在您的 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
但是,如果您在本地使用它,它將起作用,但不適用於沙箱。
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.