简体   繁体   中英

Axios catch error from Response JSON is undefined

i am returning a custom response from my php and i dont know how can i use those response for my page. Im trying to use console.log to see the status and msg but no luck.

if ($message->send()){
    return response()->json([
      'status' => 'success',
         'msg' => 'Message send =)'
   ],201);
}else{
    return response()->json([
      'status' => 'error',
         'msg' => 'Message did not send =('
   ],422);
}

and in my script

axios.post('url',params)
.then(function(){
      console.log('send');
})
.catch(function(error){
    if (error.response){
        console.log(error.response.data.msg);
    }else if(error.request){
        console.log(error.response.data.msg)
    }else{
        console.log(error.response.data.msg);
    }
});

I want to get the status and the msg but the console.log(error.response.data.msg) is undefined . Am i doing a wrong return or a wrong console.log() ?

appreciate the help.

I fixed it! i replace the function(error) to function(response). just like this

.then(function(response){
      console.log('response.data.msg');
      console.log('response.data.status');
})
.catch(function(response){
      console.log('response.data.msg');
      console.log('response.data.status');
});

Following the error response format, you need to use error.response.message to get the details of the error. At least, try to console.log(error.response) to know what's happening. Hope this help !

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