【问题标题】:res.download() throws request aborted error after executing commandres.download() 执行命令后抛出请求中止错误
【发布时间】:2020-12-17 08:41:33
【问题描述】:

我正在尝试创建一个包含一些 .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 测试它时,我收到此错误:

无法下载存档错误:请求中止

我该如何解决?感谢您的宝贵时间!

(顺便说一句,如果我尝试在else 上的 exec 中移动下载操作,它会起作用,但我希望有 2 个单独的代码块)

【问题讨论】:

    标签: javascript node.js express request http-get


    【解决方案1】:

    我想通了..

    问题出在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
        } 
    }
    

    很抱歉,我没有在这篇文章中编写整个函数,但我终于弄明白了,这很好。希望这会对某人有所帮助。所以要小心:永远不要在res.download 之后使用res.renderres.sendres.end 等。您需要先完成下载。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 2017-11-07
      • 1970-01-01
      • 2018-12-02
      • 2015-12-26
      • 1970-01-01
      • 2018-02-21
      相关资源
      最近更新 更多