简体   繁体   中英

When response.data is an empty array:- Uncaught (in promise) TypeError: Cannot read property 'data' of undefined

I am facing difficulty when I am using one axios request in another. Especially when the response.data array is empty. Whenever response.data array is empty it gives me this error:-

Uncaught (in promise) TypeError: Cannot read property 'data' of undefined

I know many people have asked Uncaught but not with response.data Here is my code:-

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);
    }) 

Error has come from the line this.some_variable= this.anothervari.reduce((a,b) => Number(a) > Number(b) ? a : b); that was missing in the original question.

You need to give the reduce function a starting value when reducing to an array, so change to this: this.some_variable= this.anothervari.reduce((a,b) => Number(a) > Number(b) ? a : b, []);

The error could have happened during the request setup before any response was returned in which case the response object is undefined https://github.com/axios/axios#handling-errors

In case axios receives no response from the server, the error object has no response object. If you look at the example documentation here , you can see that while catching the error, they check if the response object exists or not. In your case, your request probably fails without never reaching the server so you don't have a response. In cases like this it is recommended to see if the response object exists before accessing it, as otherwise you will have an exception.

  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); }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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