【问题标题】:Axios catch error from Response JSON is undefined来自响应 JSON 的 Axios 捕获错误未定义
【发布时间】:2019-08-03 21:30:25
【问题描述】:

我正在从我的 php 返回一个自定义响应,但我不知道如何将这些响应用于我的页面。我正在尝试使用 console.log 查看状态和消息,但没有运气。

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

我想获得 statusmsg 但是 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.data.message代替msg吗?
  • 你不能调试你的js代码看看error是什么样子的吗?
  • 你应该检查你的网络,你从服务器接收到什么数据然后控制台。
  • @Carnageous 我试过了,我已经修复了我的代码。但我不知道为什么我的帖子是负面的。顺便提一句。谢谢。
  • @Kapcash 谢谢!我调试我的代码并将错误替换为响应。但我的帖子是否定的。

标签: javascript php json axios


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-11-02
    • 2017-12-02
    • 2020-10-30
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    相关资源
    最近更新 更多