【问题标题】:The browser overwrites the content of the message after receiving the response浏览器收到响应后覆盖消息内容
【发布时间】:2019-10-19 07:40:57
【问题描述】:

当我尝试从响应中获取错误消息时,我在使用 DingoAPI 和 Vue.js 时遇到了一点问题。我认为浏览器正在用默认消息替换我的自定义消息。这是我的代码:

PHP 脚本

if($request->readerId){
      Return succes (this works properly)
else{
      return $this->response->error(
           'No reader',
           400 //(or diffrent code)
      );
}

Vue.js 脚本

await axios.post(API_URL + 'card/', {
            some data
        }, {
            headers: {
                headers
            },
        }).then(({data}) => {
            context.commit(SET_RESPONSE, data);
        }).catch((error) => {
            console.log(error.message);
            throw error
        })

当我尝试在网络选项卡中查看我的消息时,我可以看到(所以 DingoAPI 正确地做到了):

{"message":"No reader","status_code":400}

但是当我使用console.log(error.message) 或试图在页面上显示它时,会出现标准错误消息:

请求失败,状态码 400

有没有办法使用 DingoAPI 设置错误消息并在我的 .js 脚本中捕获它? 也许我需要编写自己的自定义异常?

【问题讨论】:

    标签: laravel vue.js axios dingo-api


    【解决方案1】:

    你想要的是从你的错误变量中访问响应的数据。

    console.log(error.response.data.message); // No reader
    

    否则你可以登录error.response查看对象:

    console.log(error.response);
    

    如果您想知道为什么会打印请求失败,状态码为 400

    问题是当console.log尝试输出错误时,打印的是字符串表示,而不是对象结构,所以你看不到.response属性。

    来源:https://github.com/axios/axios/issues/960#issuecomment-309287911

    【讨论】:

    • 就是这样!我为我感到羞耻,它是如此简单
    猜你喜欢
    • 2016-04-28
    • 1970-01-01
    • 2015-02-06
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多