【问题标题】:How do I serve a file from S3 through Meteor Iron Router如何通过 Meteor Iron 路由器从 S3 提供文件
【发布时间】:2014-04-26 06:44:42
【问题描述】:

我的问题与this one 非常相似,this one 描述了如何使用 Iron Router 提供本地文件。我需要这样做,但不是从磁盘同步读取文件,我需要从 S3 获取文件,这是一个异步调用。

问题似乎是 action 方法在异步 s3.getObject 完成之前返回给我以下错误。

Error: Can't render headers after they are sent to the client.

当 Iron Router 意识到我没有在我的 action 方法中处理响应时,我假设 Iron Router 正在为我生成响应,但我不知道如何告诉它等待我的异步调用完成。

这是我的代码。

Router.map(function () {
    this.route('resumeDownload', {
        where: 'server',
        path: '/resume/:_id',
        action: function () {
            var response = this.response;

            var candidate = Candidates.findOne(this.params._id);
            if (!candidate || !candidate.resumeS3Key) {
                // this works fine because the method hasn't returned yet.
                response.writeHead(404);
                return response.end();
            }

            var s3 = new AWS.S3();
            s3.getObject({Bucket: 'myBucket', Key: candidate.resumeS3Key}, function (err, data) {
                if (err) {
                    // this will cause the error to be displayed
                    response.writeHead(500);
                    return response.end();
                }
                // this will also cause the error to be displayed
                response.writeHead(200, {'Content-Type': data.ContentType});
                response.end(data.Body);
            });
        }
    });
});

【问题讨论】:

    标签: amazon-s3 meteor iron-router


    【解决方案1】:

    我自己解决了这个问题。我需要在我的action 方法中使用future

    这是工作代码。

    Router.map(function () {
        this.route('resumeDownload', {
            where: 'server',
            path: '/resume/:_id',
            action: function () {
                var response = this.response,
                    candidate = Candidates.findOne(this.params._id);
    
                if (!candidate || !candidate.resumeS3Key) {
                    response.writeHead(404);
                    return response.end();
                }
    
                var Future = Npm.require('fibers/future'),
                    s3 = new AWS.S3(),
                    futureGetObject = Future.wrap(s3.getObject.bind(s3)),
                    data = futureGetObject({Bucket: 'myBucket', Key: candidate.resumeS3Key}).wait();
    
                response.writeHead(200, {'Content-Type': data.ContentType});
                response.end(data.Body);
            }
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 1970-01-01
      • 2013-08-14
      • 2016-06-03
      • 2015-10-16
      • 2015-11-30
      • 1970-01-01
      • 2016-06-22
      • 2014-04-08
      相关资源
      最近更新 更多