如何从获取托管在 S3 上的网站的 s3.getObject 中呈现 index.html?

How to render index.html from s3.getObject which fetched the website hosted on S3?

我有 AWS API 网关调用的 Lambda 函数,在该 lambda 函数上,我需要在 S3 存储桶中为网站提供服务,以便我可以控制对该网站的访问和路由。

我使用的方式如下:

const AWS = require('aws-sdk');
//*/ get reference to S3 client 
var s3 = new AWS.S3();
exports.handler = (event, context, callback) => {
    var params = {
  "Bucket": "mybucket",
  "Key": "index.html" 
    };


    s3.getObject(params, function(err, data){
       if(err) {
           callback(err, null);
       } 
       else {
           let response = {
                "statusCode": 200,
                "headers":
                {
                  "Access-Control-Allow-Origin": "*", // to 
                //   "Content-Type": "text/html"
                },
                "body": JSON.stringify(data),
                "isBase64Encoded": false
            };
           callback(null, response);
        }
    });
};

给出以下输出,这不是所需要的。

{"AcceptRanges":"bytes","LastModified":"2020-03-28T08:10:04.000Z","ContentLength":661,"ETag":"\"08ea404c1973c83c8731a80bf5852d05\"","ContentType":"text/html","Metadata":{},"Body":{"type":"Buffer","data":[60,33,68,79,67,84,89,80,69,32,104,116,109,108,62,13,10,60,104,116,109,108,32,108,97,110,103,61,34,101,110,34,62,13,10,60,104,101,97,100,62,13,10,32,32,60,116,105,116,108,101,62,66,111,111,1...}

当使用来自 S3 API 的 getObject() 时,根据 the docs 您的文件内容位于 Body 属性 作为缓冲区,因为它是异步的称呼。当 S3 代码静止 运行 时,代码的执行将继续。您需要明确等待调用的承诺来解决。

const AWS = require('aws-sdk');
var s3 = new AWS.S3();

exports.handler = (event, context, callback) => {
    var params = {
        "Bucket": "mybucket",
        "Key": "index.html" 
    };

    const data = await s3.getObject(params).promise();

    callback(null, {
        "statusCode": 200,
        "headers": {
            "Access-Control-Allow-Origin": "*",
        },
        "body": JSON.stringify(data),
        "isBase64Encoded": false
    });
};