【问题标题】:Migrate axios to fetch迁移 axios 到 fetch
【发布时间】:2021-05-30 20:38:47
【问题描述】:

我有一个 axios post call:

export async function createFriend ({
  let myData = new FormData()
  myData.append('name', name)
  myData.append('age', age)
  const response = await axios.post('/myApi/friends', myData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return response.data.id
}

我想将此迁移到 fetch 调用:

export async function createFriend ({
  let myData = new FormData()
  myData.append('name', name)
  myData.append('age', age)

  const response = await fetch('/myApi/friends', {
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: myData
  })
  return response.data.id
}

但是我收到以下错误: v-on 处理程序中的错误(Promise/async):“TypeError:无法读取未定义的属性'id'。但这在 axios 调用中没有发生。我做错了什么?

【问题讨论】:

  • 您假设fetch 响应对象的形状与axios 响应对象的形状相同。
  • 您能协助处理来自 fetch 调用的正确响应对象吗?

标签: javascript vue.js vuejs2 axios fetch


【解决方案1】:

fetch 返回一个具有 .json() 方法的承诺,您需要等待。

所以你需要把return response.data.id改成return (await response.json()).id

以下是您的问题中应用了修复程序的完整代码示例:

export async function createFriend ({
  let myData = new FormData()
  myData.append('name', name)
  myData.append('age', age)

  const response = await fetch('/myApi/friends', {
    method: 'POST',
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: myData
  })

  return (await response.json()).id
}

【讨论】:

    猜你喜欢
    • 2021-12-17
    • 1970-01-01
    • 2021-12-15
    • 2022-11-11
    • 2019-08-25
    • 2020-06-13
    • 2021-05-17
    • 1970-01-01
    • 2018-12-15
    相关资源
    最近更新 更多