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

所以我试图从客户端发送数据到服务器,然后在服务器上,我正在创build一个新的文件,并在路由器发送响应下载该文件。

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

点击一个button,我的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调用它创build文件,但无法写入文件?

我错过了什么?