繁体   English   中英

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

[英]Axios catch error from Response JSON is undefined

我正在从我的 php 返回一个自定义响应,但我不知道如何将这些响应用于我的页面。 我试图使用 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);
}

在我的脚本中

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

我想获取状态msg但 console.log(error.response.data.msg) 是undefined 我是在做错误的返回还是错误的 console.log() ?

感谢您的帮助。

我修好了它! 我将函数(错误)替换为函数(响应)。 像这样

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

遵循错误响应格式,您需要使用 error.response.message 来获取错误的详细信息。 至少,尝试通过console.log(error.response)了解发生了什么。 希望这有帮助!

暂无
暂无

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

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