用于下载使用Express.js和node.js实现的文档的按钮无法正常工作

时间:2019-06-15 14:11:52

标签: javascript node.js express

在我的项目中,我希望用户单击按钮时能够下载文档。

enter image description here

  

项目结构:

enter image description here

  

public / client.js

console.log('Client-side code running');

const button = document.getElementById('myButton');
button.addEventListener('click', function(e) {
  console.log('button was clicked');

  fetch('/clicked', {method: 'POST'})
    .then(function(response) {
      if(response.ok) {
        console.log('Click was recorded');
        return;
      }
      throw new Error('Request failed.');
    })
    .catch(function(error) {
      console.log(error);
    });
});
  

public / index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Report Generation</title>
  </head>
  <body>
    <h1>Download your document!</h1>
    <button id="myButton">Click me!</button>
  </body>
  <script src="client.js"></script>
</html>
  

server.js

    console.log('Server-side code running');

    const express = require('express');
    const createDocumentService = 

    const app = express();

    // serve files from the public directory
    app.use(express.static('public'));

    // start the express web server listening on 8080
    app.listen(8081, () => {
      console.log('listening on 8080');
    });

    // serve the homepage
    app.get('/', (req, res) => {
      res.sendFile(__dirname + '/index.html');
    });
 app.get('/download', function(req, res){
         setTimeout(() => {
          res.download(path.join(__dirname, 'docs/doc1.txt'), function (err) {

              console.log(err);

          });
      }, 500)
      });


    app.post('/clicked', (req, res) => {
      const click = {clickTime: new Date()};
      console.log(click);

      setTimeout(() => {
          res.download(path.join(__dirname, 'docs/doc1.txt'), function (err) {

              console.log(err);

          });
      }, 500)
    });

运行应用程序并单击按钮后:
enter image description here

当用户单击按钮时,由于以下原因,他应该会看到正在下载的报告文件:

  

在client.js中

button.addEventListener('click', function(e) {
  console.log('button was clicked');

  fetch('/clicked', {method: 'POST'})
    .then(function(response) {
      if(response.ok) {
        console.log('Click was recorded');
        return;
      }
      throw new Error('Request failed.');
    })
    .catch(function(error) {
      console.log(error);
    });
});
  

在service.js中:

app.post('/clicked', (req, res) => {
      const click = {clickTime: new Date()};
      console.log(click);

      setTimeout(() => {
          res.download(path.join(__dirname, 'docs/doc1.txt'), function (err) {

              console.log(err);

          });
      }, 500)
    });

但是,该文档未下载。
但是,当我连接到

  

localhost:5353 /下载

我为下载文档编写的相同代码/逻辑写在按钮POST路由内,可以完美地工作,并且确实可以下载文档。
因此,我真的不明白为什么相同的代码对一个“正常”路由有效,而对依赖于按钮的另一种路由无效。

谢谢!

1 个答案:

答案 0 :(得分:1)

您无法使用ajax下载文件,因为Javascript无权写入文件。您可以只使用href链接,也可以使用window.location,它将正常工作。

HTML:

<a href="/download" class="button">Click me!</a>

使用.button类将链接的样式设置为按钮。

JS:

button.addEventListener('click', function(e) {
  console.log('button was clicked');
  window.location="./download"
  // or window.open(url, '_blank') for new window.
});