无法从 axios 函数之外的 axios GET 请求响应中读取值
Posted
技术标签:
【中文标题】无法从 axios 函数之外的 axios GET 请求响应中读取值【英文标题】:Cannot read value from axios GET request response outside of axios function 【发布时间】:2021-11-17 01:10:47 【问题描述】:我正在尝试创建一个任务跟踪器。 后端是 mysql,API 是使用 Node JS 和 Express JS 构建的,前端是 React JS。
我正在尝试为我从 GET 请求中获得的响应分配一个变量。
the request works in PostMan
在我的前端,我尝试使用以下代码分配变量。 如上所示,get 请求在 PostMan 中有效。
Code
const baseURL = 'http://localhost:5000/api/user/timesheet/13009';
let y = [];
axios.get(baseURL).then((response)=>
for( var i in response.data)
y.push( response.data[i]);
console.log(y);
);
Output
这是终端的输出。我可以使用像 y[0] 这样的索引并获得那个特定的值。但是当我删除打印语句并将其放在代码下方时,y 的值会发生变化。
const baseURL = 'http://localhost:5000/api/user/timesheet/13009';
let y = [];
axios.get(baseURL).then((response)=>
for( var i in response.data)
y.push( response.data[i]);
);
console.log(y);
Secound Output
我得到了这个输出,但是 y.length 设置为 0,我无法读取 y 中的数据。
const baseURL = 'http://localhost:5000/api/user/timesheet/13009';
let y = [];
axios.get(baseURL).then((response)=>
for( var i in response.data)
y.push( response.data[i]);
);
console.log(y);
console.log('y.length');
console.log(y.length);
console.log('y[0]');
console.log(y[0]);
Third Output
这表明索引没有值并且数组为空。 究竟是什么导致了这个问题,如何解决?
【问题讨论】:
这能回答你的问题吗? How to return the response from an asynchronous call 【参考方案1】:我认为是因为您在“then()”中设置的工作是在 axios 请求生效后执行的,此时您的数据已成功恢复。 axios调用之后的代码(一个promise)在promise之前/同时执行,意味着数据还没有被恢复。
【讨论】:
【参考方案2】:就像@Nevermore1803 所说,axios 会在一段时间后返回你的请求。
因此,您将值从 axios 推送到的数组 y
很可能在 axios 从请求中得到响应时仍未填充。
您可以通过以下方式自行查看
axios.get(baseURL).then((response)=>
for( var i in response.data)
y.push( response.data[i]);
console.log('1')
);
console.log('2')
您可以看到1
将在 2
之后出现,因此为了使用您的阵列,在您尝试使用他之前,您需要检查他是否已经被填充并且然后继续与他合作。
检查你的数组是否为空的一种方法是>>if(array.length > 0)... do something
另外,如果你正在使用 react,你应该开始使用它的钩子,比如 useState 来处理这样的数据。
【讨论】:
以上是关于无法从 axios 函数之外的 axios GET 请求响应中读取值的主要内容,如果未能解决你的问题,请参考以下文章
如何从我得到的数组中获取特定的数组元素作为调用 axios.get() 调用的函数的响应 [重复]
无法从 reactjs 中的 axios 向 id=1 文章的 django REST API 后端发出 GET 请求