【问题标题】:Can I delay PUT upload in Express until my server finishes an operation?我可以在我的服务器完成操作之前延迟 Express 中的 PUT 上传吗?
【发布时间】:2016-09-20 21:38:51
【问题描述】:

我有一个服务器通过 PUT 接收文件,然后将它们存储在 S3 中。

在客户端 PUT 文件后,它通常会立即请求它们以换取渲染。不幸的是,我的服务器需要一些时间来实际处理上传并将它们存储在 S3 中。

这是我在 Express 中使用的代码:

    req.pipe(writeStream);

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'PUT, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type');


    if ('OPTIONS' === req.method) {
        res.sendStatus(200);
        res.end('OK!');
        return;
    }

    if ('PUT' === req.method) {

        writeStream.on('error', () => {
            res.sendStatus(500);
        });

        writeStream.on('close', async () => {
            // This might take 30s
            await this.storage.store(fn, args.blobID);

            // This does not seem to have any effect
            // I would like to prevent the client from 'finishing' the
            // PUT request before I say it is done.
            res.end('OK!')
        });

        res.sendStatus(200);
    }

理想情况下,我可以“暂停”客户的 PUT 请求,直到 storage.store() 完成,确保文件实际可用。

有什么办法可以做到吗?

另外,我不确定sendStatus() / end() 电话,如果我混淆了,请随时发表评论。

附:我知道,在理想情况下,我只会分发签名的 URL,让客户端直接上传到 S3,但我需要 AES256 加密......

【问题讨论】:

    标签: http express browser amazon-s3


    【解决方案1】:

    我不熟悉 S3 上传,但我想会有一个回调(例如向您发送回复(成功或失败...等))。 (如果没有,请告诉我)

    S3.upload(data,function(response){ // something like this
      // then, you can callback
      // ...
      // res.end() or res.sendStatus(...)
    })
    

    据我所知,Express 不会自动发送超时,因此您只需将响应放入 S3 的响应函数中,这样您的请求就不会在您的存储结束之前结束。

    来自Must res.end() be called in express with node.js?

    如果调用 res.send(),则不必调用 res.end()。 res.send() 为你调用 res.end()。

    并且 res.sendStatus() 等于 res.status(...).send(message or code)(通过http://expressjs.com/en/api.html

    所以,res.sendStatus() 会调用 end()。

    【讨论】:

    • 谢谢。但是,我似乎必须调用res.sendStatus(200); 才能触发实际的客户端上传。另外,store函数是async,会等待S3上传完成。
    猜你喜欢
    • 2014-02-27
    • 1970-01-01
    • 2023-04-04
    • 2012-01-28
    • 2020-10-26
    • 2021-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多