【问题标题】:Why do I get this undefined property error message in my promise?为什么我会在我的承诺中收到这个未定义的属性错误消息?
【发布时间】:2020-02-03 01:03:09
【问题描述】:

当我的axios调用失败时,catch()中的代码正确显示err.response.data.message中包含的错误信息,这是定义的。

但是当axios 调用成功时,我在控制台中得到这个错误:

Uncaught (in promise) TypeError: Cannot read property 'data' of undefined

如何解决?

这是我的axios 电话代码:

mounted () {
  this.$axios.$get(`http://example.com/wp-json/project/v1/post/${this.$route.params.id}`)
    .then((res) => {
      this.title = res.post_title
      this.content = res.post_content
    })
    .catch((err) => {
      this.$toast.error(err.response.data.message)
    })

【问题讨论】:

  • console.log()err的内容了吗?正如错误消息非常清楚地指出的那样,err.response 未定义。
  • 是的,无论 axios 调用是否成功,它都不会起作用。但是当 axios 调用失败时 $toast.error 可以正常工作。很奇怪

标签: vue.js promise axios


【解决方案1】:

尝试res.data.post_title 而不是res.post_title

...
.then((res) => {
  this.title = res.data.post_title
  this.content = res.data.post_content
})
...

axios返回一个包含以下信息的对象

{
  data: {},        // the response that was provided by the server
  status: 200,     // the HTTP status code from the server response
  statusText: 'OK',// the HTTP status message from the server response
  headers: {},     // the headers that the server responded with
  config: {},      // the config that was provided to `axios` for the request
  request: {}      // the request that generated this response
}

如果你窃取了同样的错误,那么它可能是一个服务器端格式错误的数据,尝试 console.log 响应并查看服务端是否有任何问题。

...
.then((response) => {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });
...

【讨论】:

    猜你喜欢
    • 2016-06-08
    • 1970-01-01
    • 2011-08-07
    • 2015-01-25
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 2022-11-19
    • 1970-01-01
    相关资源
    最近更新 更多