【问题标题】:How to display response error message with axios如何使用 axios 显示响应错误消息
【发布时间】:2017-11-07 05:25:55
【问题描述】:

现在几个月来一直希望实现这一目标,但现在需要它。我需要显示错误消息,设置在服务器上,关于出了什么问题:

服务器端点

abort(406, 'Foo bar!')

网页:

[...]
 .catch(e => {
  console.log(e.response.data) // does not work
 })

在 chrome 开发工具中,在预览下,我看到了消息 Foo bar!。如何在我的控制台日志中获取此消息?

此端点将根据操作有不同的abort 消息,因此我不想在网络上为错误设置静态错误消息。

Chrome 开发工具消息:

【问题讨论】:

标签: javascript httpresponse axios


【解决方案1】:

这应该可以工作:console.log(e.response.data.message)。我想这就是你要找的。​​p>

这是针对这种类型的请求:

axios.post(
    url,
    {},
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error.response.data.message);
    });

【讨论】:

  • 没有返回我设置的消息:Foo bar!
  • 你用 e.message 试过了吗?
  • 我收到了Request failed with status code 406。如果这有所不同,我会使用 Laravel。但 Chrome 开发工具显示实际消息 Foo bar!
  • 第 4 行缺少“{”
【解决方案2】:

我遇到过这个问题。我创建了一个axios实例,responseType是'json', axios.create({ ... responseType: 'json' })

response type 不是json,所以看不懂。去掉这个属性可以解决这个问题

【讨论】:

  • 你能详细说明一下为什么去掉responseType可以解决这个问题吗?
  • 服务器返回的response content-type不是json,是'arraybuffer', 'blob', 'document', 或者其他,我设置的是json,所以取不到其他类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 2016-10-16
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 2021-12-02
  • 2016-12-17
相关资源
最近更新 更多