javascript - Res.download() 使用 html 表单提交但不是 Axios post 调用

标签 javascript node.js reactjs http axios

我正在编写一个小应用程序,它将信息从 React 应用程序提交到 Express 服务器的“/download”API,然后将新文件写入本地文件系统并使用 Express 在客户端下载新创建的文件fs.writeFile() 回调中的 res.download()。

我一直在使用常规的 html 表单提交来发布数据,但由于复杂性的增加,我已经切换到使用 Axios,但它不再有效。

奇怪的是只有客户端的下载好像停止了。写入文件工作正常,所有控制台日志记录都是相同的(下面的“文件已下载!”日志)。当我切换回表单提交时,它会继续工作,所以唯一的变化是使用 Axios 发送发布请求。据我所知,一旦数据到达那里,两者之间应该没有任何区别,但我希望有人比我对此有更深入的了解。

除了在表单和 Axios post 请求之间进行测试外,我还尝试将 Axios 请求的内容类型从“application/json”更改为“x-www-form-urlencoded”,认为匹配内容输入表单发送的内容可能就是答案

以下是相关应用程序的相关代码片段:

server.js( Node JS)

app.post('/download', (req, res) => {
  console.log("Requst data");
  console.log(req.body.html);


  fs.writeFile("./dist/test.txt", res.body.test,
    (err) => {
      if(err) {
        return console.log(err);
      } else{
        console.log("The file was saved!");
      }

      let file = __dirname + '/text.txt';
      /*This is the issue, the file is not downloading client side for the Axios iteration below*/
      res.download(file,(err)=>{
        if(err){
          console.log(err);
        } else {
          console.log(file);
          /*This logs for both View.js iterations below*/
          console.log("File downloaded!");
        }
      });
    });
})

App.js( react )

handleSubmit(e){
    e.preventDefault();

    axios.post(`/download`, {test: "test"})
      .then(res => {
        console.log("REQUEST SENT");
      })
      .catch((error) => {
        console.log(error);
      });
}

render(){
      return(
        <div>
          <View handleSubmit={this.handleSubmit} />
        </div>
      )
}

View.js( react )

这个有效:

render(){
      return(
        <form action="/download" method="post">
            <input type="submit">
        </form>
      )
}

不会在客户端启动下载,但在其他方面工作得很好:

render(){
      return(
        <form onSubmit={this.props.handleSubmit}>
            <input type="submit">
        </form>
      )
}

我没有收到任何错误,一切似乎都正常工作,除了在客户端下载。

预期的结果是文件在客户端使用 Axios 下载,但事实并非如此。

更新:Bump,没有得到任何关注

最佳答案

实际上,您可以通过一些 blob 操作在 Ajax POST 请求中下载文件。下面列出了示例代码,并附有解释注释:

handleSubmit(e){
  var req = new XMLHttpRequest();
  req.open('POST', '/download', true); // Open an async AJAX request.
  req.setRequestHeader('Content-Type', 'application/json'); // Send JSON due to the {test: "test"} in question
  req.responseType = 'blob'; // Define the expected data as blob
  req.onreadystatechange = function () {
    if (req.readyState === 4) {
      if (req.status === 200) { // When data is received successfully
        var data = req.response;
        var defaultFilename = 'default.pdf';
        // Or, you can get filename sent from backend through req.getResponseHeader('Content-Disposition')
        if (typeof window.navigator.msSaveBlob === 'function') {
          // If it is IE that support download blob directly.
          window.navigator.msSaveBlob(data, defaultFilename);
        } else {
          var blob = data;
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = defaultFilename;

          document.body.appendChild(link);

          link.click(); // create an <a> element and simulate the click operation.
        }
      }
    }
  };
  req.send(JSON.stringify({test: 'test'}));
}

对于后端,没有什么特别的,只是一个普通的res.download语句:

app.post('/download', function(req, res) {
  res.download('./example.pdf');
});

对于 axios,前端代码如下所示:

axios.post(`/download`, {test: "test"}, {responseType: 'blob'})
  .then(function(res) {
        ...
        var data = new Blob([res.data]);
        if (typeof window.navigator.msSaveBlob === 'function') {
          // If it is IE that support download blob directly.
          window.navigator.msSaveBlob(data, defaultFilename);
        } else {
          var blob = data;
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = defaultFilename;

          document.body.appendChild(link);

          link.click(); // create an <a> element and simulate the click operation.
        }
  })
  .catch((error) => {
    console.log(error);
  });

关于javascript - Res.download() 使用 html 表单提交但不是 Axios post 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56652397/

相关文章:

javascript - 如何正确传递 Javascript 属性以便它们可以被函数修改

javascript - 如何从 firefox-addon/js-ctypes 调用 C++ 类实例?

javascript - 菜单栏仅更改一个 div 中的内容

node.js - 微软机器人- Node SDK : How to mention a user in Microsoft Teams

node.js - MEAN 堆栈安装给出 304 和 404s

javascript - useLocation 状态即将为 null

javascript - 如何知道用户是否使用 reactjs 连接到蜂窝网络或 wifi

javascript - 在标签名称中创建新的 HTML 属性时出现问题

node.js - 如何使用 phantomjs 作为 npm 包

reactjs - Ant Design Table 组件 onChange 回调未触发