Res.download() working with html form submit but not an Axios post call

后端 未结 2 1668
时光说笑
时光说笑 2021-01-07 10:55

I am writing a small app that submits information from a React app to an Express server\'s \"/download\" API where it then writes a new file to the local file system and dow

2条回答
  •  迷失自我
    2021-01-07 11:11

    The browser won't handle the response of a POST request as a file download, so you either need to make another request or handle the response differently.

    Below is an example of making another request, to go fetch the file after it's been created on the back-end. The other answer gives a nice example of using the Blob API to process the response data directly from the POST request.

     axios.post(`/download`, {test: "test"})
      .then(res => {
        console.log("REQUEST SENT");
    
        // Send back an identifier, or whatever so that you can then
        // retrieve the file with another request. 
    
        // res.id is hypothetical, you simply need to be able to access the file
        // whether by filename, id, however you want.
        window.open("/download?id=" + res.id);
      })
      .catch((error) => {
        console.log(error);
      });
    

提交回复
热议问题