将数据发送到Node JS中的服务器以下载文件

时间:2017-11-22 19:00:32

标签: javascript node.js ajax express

所以我试图将数据从客户端发送到服务器,然后在服务器上我创建一个新文件,在路由器中我发回回应该下载该文件。

但我无法实现。我正在使用AJAX调用。以下是我的代码:

单击按钮时我的Ajax调用:

   $.ajax({
      type: 'POST',
      url: '/createDownloadFile',
      data: JSON Object,
    }).done(() => {
      window.open('/download');
    });

在express.js中:

  app.post('/createDownloadFile', (req, res) => {
    downloadFile.createDownloadFile(req);
    res.send('SUCCESS');
  });

下载JS中的文件:

const fs = require('fs');
const path = require('path');


module.exports.createDownloadFile = (request) => {
  if (request) {
    let filePath;
    const userID = 'xyz';
    filePath = path.join(__dirname, userID.concat('.txt'));
    const dataToWrite = request.body;
    fs.openSync(filePath, 'w', (err) => {
      if (err) throw new Error('FILE_NOT_PRESENT');
    });
    fs.appendFileSync(filePath, JSON.stringify(dataToWrite, null, 4), (err) => {
    if (err) throw new Error('FILE_WRITE_ERROR');
     });
    return filePath;
  }
};

另外,在我的router.js文件中:

  router.get('/download', (req, res) => {
    const filePath = makeDownloadFile.createDownloadFile(req);
    res.download(filePath);
  });

但是当我调用AJAX调用时,它似乎会创建文件,但无法在文件中写入?

我缺少什么?

0 个答案:

没有答案