res.download()不工作在我的情况

我正在使用nodejs和expressjs框架从服务器下载文件“jsonFile.json”。

我正在使用下面的代码

res.get('/download', function(req, res) { res.setHeader('Content-disposition', 'attachment; filename=jsonFile.json'); res.setHeader('Content-Type', 'text/json'); res.download(__dirname + 'jsonFile.json'); } }); 

但是这会导致整个文件内容的响应。

我期待浏览器问我要保存在本地磁盘的文件。

我如何将文件保存在本地磁盘?

让快速设置正确的标题,只是这样做:

 res.get('/download', function(req, res) { res.download(__dirname + 'jsonFile.json', 'jsonFile.json'); }); 

( doc )

编辑:因为你通过AJAX呼叫请求/download ,你必须改变你的设置,因为大多数(所有?)浏览器将不会显示下载对话框。

相反,您可以从前端代码创build一个新窗口来触发对话框:

 window.open('/download?foo=bar&xxx=yyy');