javascript - res.download() 执行命令后抛出请求中止错误
问题描述
我正在尝试创建一个包含一些 .txt 文件的存档,然后我想下载这个存档。请看下面的代码:
async function archiveAndDownload(res) {
const bashCommand = ...
const archive = ...
exec(bashCommand, (err, stdout, stderr) => {
if (err && err.code != 1) {
console.log(err);
res.status(500).json({ error: `Error.` });
return;
} else {
if (stderr) {
console.log(stderr);
}
}
});
res.status(200).download(archive, async (err) => {
if (err) {
console.log("Cannot download the archive " + err);
} else {
fs.unlink(archive);
}
});
}
async function getX(req, res) {
try {
await archiveAndDownload(res);
} catch (err) {
console.log("Error: " + err);
}
}
尝试从 Postman 对其进行测试时,出现此错误:
无法下载存档错误:请求中止
我该如何解决?感谢您的时间!
(附带说明,如果我尝试在 exec on 中移动下载操作else
,它会起作用,但我希望有 2 个单独的代码块)
解决方案
我想到了..
问题在于getX
功能。可悲的是我忘记了finally
最后有一个块总是执行..
所以整个getX
功能是:
async function getX(req, res) {
try {
await archiveAndDownload(res);
} catch (err) {
console.log("Error: " + err);
} finally {
res.end(); // <<<< this was my problem, I removed the whole finally block
}
}
很抱歉我没有在这篇文章中写出整个函数,但我终于弄明白了,这很好。希望这会对某人有所帮助。所以要小心:不要在 a 之后使用res.render
,res.send
等。您需要先完成下载。res.end
res.download
推荐阅读
- windows-server-2012 - SCHTASKS 不会在预定时间自动执行
- css - 达到所需长度后文字消失
- c# - 使用基本身份验证调试本地 WCF 服务始终返回 401 - 未经授权
- python - python更改行的列
- python - Django(1.4 ...)'Pincode'解密不起作用
- python - Tensorflow:gen_nn_ops.max_pool_grad_v2() 是如何工作的?
- c# - 防止在实体框架中保存子对象
- c# - windows server 2012下IIS中获取.exe程序的输出
- java - 将两个数组相加,求出 10 的可能组合数
- javascript - 下载属性不起作用(不是跨域)