【问题标题】:how to send files and data with axios in react? [duplicate]如何在反应中使用axios发送文件和数据? [复制]
【发布时间】:2021-03-06 21:51:22
【问题描述】:

后端期待类似的东西

    {
       "key" : "xyz"
}// and two files

我试过下面的代码,但它总是显示 url 中传递的空参数

 const obj = {
        key : [this.state.key]
      };
      const json = JSON.stringify(obj);
      const blob = new Blob([json], {
        type: 'application/json'
      });
      const data = new FormData();
      data.append("params", blob);
      data.append("data1",this.state.file1)
      data.append("data2",this.state.file2)
      
        let res= await axios.get(url,data);
        console.log(res)

【问题讨论】:

标签: javascript reactjs axios


【解决方案1】:

您不能将 formData 与 get 一起使用,为了与 body 一起发送,文件上传必须是一个 post 请求。

let res= await axios.post(url,data);

【讨论】:

    【解决方案2】:

    您不能使用 get 方法发送数据(正文)。我认为你需要使用 post 方法。

     const obj = {
            key : [this.state.key]
          };
          const json = JSON.stringify(obj);
          const blob = new Blob([json], {
          type: 'application/json'
          });
          const data = new FormData();
          data.append("params", blob);
          data.append("data1",this.state.file1)
          data.append("data2",this.state.file2)
          
          let res= await axios.post(url,data);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-14
      • 2021-06-17
      • 2021-08-18
      • 2017-09-27
      • 1970-01-01
      • 2021-12-09
      • 2022-01-15
      • 2018-07-10
      相关资源
      最近更新 更多