You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将fetch请求重构为async/await形式的axios请求并获取相同结果

核心问题原因

你写的axios代码存在2个关键错误,才会出现无法正常传参、拿不到返回值的问题:

  • axios.post的参数顺序错误:axios.post的参数规范是axios.post(请求地址, 请求体对象, 配置项),你现在把headers和请求体都塞到了第二个参数里,导致请求格式完全不符合预期
  • 不了解axios和fetch的响应结构差异:axios会自动序列化请求体、自动解析JSON响应,不需要手动调用JSON.stringify和response.json(),后端返回的原始数据都存放在响应对象的data字段下;且axios默认仅2xx状态码会进入.then回调,非2xx直接触发catch,不用手动判断response.ok,要对齐fetch的逻辑只需要加个配置即可

对齐原fetch逻辑的axios实现

async/await写法(和原代码逻辑完全一致)

const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + userJWT
}
try {
  const response = await axios.post(visitURL, endingVisit, {
    headers,
    // 加这行配置让所有状态码都返回,对齐fetch的行为
    validateStatus: () => true
  })
  // 等价原fetch的response.ok判断
  if (response.status >= 200 && response.status < 300) {
    // 直接从data字段拿解析好的返回值,无需手动调用json()
    const { visitId, createdAt } = response.data
    const viewVisitDto = new ViewVisitDto(`${visitId}${createdAt}${visitorId}${doctorId}${oldPatientId}`)
    return viewVisitDto
  } else {
    throw new Error("deactivated!")
  }
} catch (error) {
  console.log(error)
  throw error
}

.then回调写法(和你现有写法对齐)

const headers = {
  'Content-Type': 'application/json',
  'Authorization': 'Bearer ' + userJWT
}
axios.post(visitURL, endingVisit, {
  headers,
  validateStatus: () => true
}).then(response => {
  if (response.status >= 200 && response.status < 300) {
    const { visitId, createdAt } = response.data
    const viewVisitDto = new ViewVisitDto(`${visitId}${createdAt}${visitorId}${doctorId}${oldPatientId}`)
    // 这里处理你的业务逻辑即可
  } else {
    throw new Error("deactivated!")
  }
}).catch(error => {
  console.log(error)
})

node-fetch TypeScript报错解决

如果你的Node版本是18及以上,Node已经内置了全局fetch实现,不需要额外安装node-fetch和对应的类型包,只需要把tsconfig.json的compilerOptions.lib数组中添加DOM,或者把target设置为ES2022及以上,即可正常识别fetch类型,不会出现报错。


内容的提问来源于stack exchange,提问作者Daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 11:45:06