当我在另一个 axios 请求中使用一个 axios 请求时,我遇到了困难。特别是当 response.data 数组为空时。每当响应数据数组为空时,它都会给我这个错误:-
未捕获(在承诺中(类型错误:无法读取的属性"数据" 定义
我知道很多人问过Uncatch,但没有回应。这是我的代码:-
axios.get(URL+'/xyz?variable='+variablevalue, headerconfig)
.then(response => {
this.tempvariable= (response.data);
axios.get(URL+'/abc?variable='+variablevalue,headerconfig)
.then((response) => {
this.tempvariable = (response.data);
//inside for loop by using this.tempvariable
this.some_variable= this.anothervari.reduce((a,b) => Number(a) > Number(b) ? a : b);
})
.catch(e => {
alert(e.response.data);
})
})
.catch(e => {
alert(e.response.data);
})
错误来自原始问题中缺少的行this.some_variable= this.anothervari.reduce((a,b) => Number(a) > Number(b) ? a : b);
。
当归约到数组时,您需要为 reduce 函数提供一个起始值,因此请更改为以下内容:this.some_variable= this.anothervari.reduce((a,b) => Number(a) > Number(b) ? a : b, []);
在返回任何响应之前,错误可能发生在请求设置期间,在这种情况下,响应对象未定义https://github.com/axios/axios#handling-errors
如果 axios 没有收到来自服务器的响应,则错误对象没有响应对象。如果您查看此处的示例文档,您可以看到在捕获错误时,它们会检查响应对象是否存在。在您的情况下,您的请求可能会失败,而不会到达服务器,因此您没有响应。在这种情况下,建议在访问响应对象之前查看它是否存在,否则您将遇到异常。
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});