首页 > 解决方案 > 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 个单独的代码块)

标签: javascriptnode.jsexpressrequesthttp-get

解决方案


我想到了..

问题在于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.endres.download


推荐阅读