header 之前的 HTTP 请求有附件

HTTP requests until header has attachment

我们有一个 Web 应用程序,它会在访问 url 时准备并生成一个 .zip 文件,然后下载该文件。

我需要使用 requestjs 创建一个 nodejs 应用程序,它可以一直发出请求,直到有附件 header,然后才会下载附件。

生成 .zip 文件的页面包含一条简单的 html 消息,说明正在准备下载文件。使用 javascript reload(true) 函数在加载时调用。

我不确定这样做是否正确,但我愿意接受建议。

您可以使用 async.until 循环一些逻辑,直到 header 可用:

let success = true;
async.until(
    // Do this as a test for each iteration
    function() {
        return success == true;
    },
    // Function to loop through
    function(callback) {
        request(..., function(err, response, body) {
            // Header test
            if(resonse.headers['Content-Disposition'] == 'attatchment;filename=...') {
                response.pipe(fs.createWriteStream('./filename.zip'));
                success = true;
            }
            // If you want to set a timeout delay
            // setTimeout(function() { callback(null) }, 3000);
            callback(null);
        });
    },
    // Success!
    function(err) {
        // Do anything after it's done
    }
)

您可以使用 setInterval 等其他方法来实现,但我会选择使用 async 以获得友好的异步功能。

编辑:这是另一个使用setTimeout的例子(我不喜欢setInterval的初始延迟。

let request = require('request');

let check_loop = () => {
    request('http://url-here.tld', (err, response, body) => {
        // Edit line below to look for specific header and value
        if(response.headers['{{HEADER_NAME_HERE}}'] == '{{EXPECTED_HEADER_VAL}}') 
        {
            response.pipe(fs.createWriteStream('./filename.zip')); // write file to ./filename.zip
        }
        else
        {
            // Not ready yet, try again in 30s
            setTimeout(check_loop, 30 * 1000);
        }
    });
};

check_loop();