简体   繁体   English

来自响应 JSON 的 Axios 捕获错误未定义

[英]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.我正在从我的 php 返回一个自定义响应,但我不知道如何将这些响应用于我的页面。 Im trying to use console.log to see the status and msg but no luck.我试图使用 console.log 查看状态和 msg 但没有运气。

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 .我想获取状态msg但 console.log(error.response.data.msg) 是undefined Am i doing a wrong return or a wrong console.log() ?我是在做错误的返回还是错误的 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.遵循错误响应格式,您需要使用 error.response.message 来获取错误的详细信息。 At least, try to console.log(error.response) to know what's happening.至少,尝试通过console.log(error.response)了解发生了什么。 Hope this help !希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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