【问题标题】:How to send POST response to another function using React.js and axios?如何使用 React.js 和 axios 将 POST 响应发送到另一个函数?
【发布时间】:2021-02-25 21:34:14
【问题描述】:

我有fileUploadHandler 函数,如下所示 POST 文件。 帖子的回复如下:{ filename: '123sdfg.xlsx' }

fileUploadHandler = (fileData) => {
    const formData1 = new FormData();
    formData1.append("file", fileData)
    postFileUpload(formData1).then((result) => console.log("response", result.data));    
  };

我尝试了下面的代码,但抛出了 storeFile undefined 的错误。

fileUploadHandler = (fileData) => {
    const formData1 = new FormData();
    formData1.append("file", fileData)
    postFileUpload(formData1).then((result) => storeFile(result.data)); 
    storeFile;
  };

后调用函数如下:

export const postFileUpload = (values) => {
  return new Promise((resolve, reject) => {
    axios    
    .post('<URL>', values)
    .then((result) => {
      if (result) {
        resolve(result);
      }
    })
    .catch((error) => {
      reject({ message: "Error:" + error.message });
    });
  });
}

我希望处理程序不仅可以发布文件,还可以获取响应,并将响应发送到另一个函数。 如何将 fileUploadHandler 的响应返回给 formSubmit 等其他函数(示例)。

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    我认为这可能是您正在寻找的。如果您想使用 axios 发送文件,您可能还需要添加一个标头来指定内容类型。

    const fileUploadHandler = fileData => {
      const formData1 = new FormData()
      formData1.append("file", fileData)
    
      axios
        .post("<URL>", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then(result => {
          if (result) {
            postFileUpload(result)
          }
        })
        .catch(error => {
          // Handle any errors if the upload fails
          console.log(error)
        })
    }
    
    const postFileUpload = result => {
      // This will be called after the file is uploaded.
      console.log(result)
    }
    

    编辑:

    const postFileUpload = formData => {
      return axios.post("<URL>", formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
    }
    
    const fileUploadHandler = fileData => {
      const formData1 = new FormData()
      formData1.append("file", fileData)
    
      postFileUpload(formData1)
        .then(result => {
          console.log("response", result.data)
        })
        .catch(error => {
          // Handle any errors if the upload fails
          console.log(error)
        })
    }
    

    【讨论】:

    • 没有。我不想将 postFileUpload 合并到 fileUploadHandler 中,这两个函数位于 2 个不同的文件夹中。我想要下面的东西,但它会抛出未定义 storeFile 的错误。 fileUploadHandler = (fileData) =&gt; { const formData1 = new FormData(); formData1.append("file", fileData) postFileUpload(formData1).then((result) =&gt; storeFile(result.data)); storeFile };
    • 请查看我对问题所做的编辑。第二块代码是我尝试过的,但会引发错误。我希望 fileUploadHandler 函数返回一个类似 storeFile 的常量。
    猜你喜欢
    • 2022-01-14
    • 1970-01-01
    • 2016-07-11
    • 2022-01-26
    • 2021-03-24
    • 2021-01-10
    • 2021-05-12
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多