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

React中使用Axios post方法导出文件报400 Bad Request问题求解

React 事故数据导出400错误排查方案

常见原因与对应解决方法

  • 参数字段/类型不符合后端要求
    首先确认后端接口要求的请求参数名是否和你传递的r_type、incident_number完全一致,常见错误包括字段名拼写错误(比如后端要求report_type而非r_type、incident_no而非incident_number)、参数类型不匹配(你当前将incident_number转为字符串传递,若后端要求数字类型也会触发校验失败)。
    解决方法:打开浏览器开发者工具「网络」面板,查看实际发出的请求Payload,和接口文档要求的参数逐一比对,调整参数名或类型即可。
  • 请求Content-Type与后端要求不匹配
    Axios默认传递对象参数时会使用application/json格式编码,如果后端接口要求application/x-www-form-urlencoded或者multipart/form-data格式的参数,就会返回400错误。
    解决方法:
    1. 若要求x-www-form-urlencoded格式,使用qs库序列化参数,修改请求配置:
    import qs from 'qs'
    // 发送请求时调整配置
    await axios.post(`/internal_incident/export-incident/`, qs.stringify(data),{
      responseType: 'arraybuffer',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
    
    1. 若要求form-data格式,使用FormData包装参数:
    const formData = new FormData()
    formData.append('r_type', data.r_type)
    formData.append('incident_number', data.incident_number)
    await axios.post(`/internal_incident/export-incident/`, formData,{
      responseType: 'arraybuffer'
    })
    
  • 接口路径或请求方法错误
    确认你填写的接口路径/internal_incident/export-incident/是否和后端提供的完全一致,有没有缺失部署前缀、多写/漏写斜杠的问题,同时确认接口是否确实接收POST请求。
    解决方法:核对接口文档的路径与请求方法,修正错误即可。
  • incident_number为空/非法值
    若调用接口时this.state.incident_number为undefined、空值或者不符合后端校验规则的内容,也会触发400错误。
    解决方法:接口调用前增加参数合法性校验:
    IncidentDataExport =async (report_type) => {
      // 新增参数校验
      if(!this.state.incident_number) {
        console.log('事故编号为空,无法导出')
        return
      }
      // 原有逻辑
    }
    

附加优化建议

你当前代码中async/await和then/catch混用,逻辑可以更简洁,统一使用try/catch捕获错误即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 06:06:03