如何通过Node ExpressJS从S3提供静态网站?

10

目前我在我的Node.js Express应用程序中使用app.use(express.static('public')),并且我的文件位于public文件夹中,它可以正常工作。 但是,我想将这些文件(如index.html等)存储在我的S3存储桶中(以便多个应用程序可以使用此网站)。 我尝试过

app.get('/', function(req, res) {
    res.sendfile('link-to-s3-file/index.html'); 
 });

一直未能成功...

2个回答

15

我不想重复造轮子。在npm上有一个相当新的、文档记录良好的中间件模块可以用于此。

从文档中可以得知:

app.get('/media/*', s3Proxy({
  bucket: 'bucket_name',
  prefix: 'optional_s3_path_prefix',
  accessKeyId: 'aws_access_key_id',
  secretAccessKey: 'aws_secret_access_key',
  overrideCacheControl: 'max-age=100000'
}));

3

我希望/foo能够匹配不同s3存储桶中的/foo.html。我使用了以下方法:

app.get('/:thePath', function(req, res) {
    var key = "saved/" + req.params.thePath;
    if(key.indexOf(".html") === -1) {
        key = key + ".html";
    }

    s3.getObject({ Bucket: "just-read", Key: key })
   .on('httpHeaders', function (statusCode, headers) {
        res.set('Content-Length', headers['content-length']);
        res.set('Content-Type', "text/html");
        this.response.httpResponse.createUnbufferedStream()
            .pipe(res);
    })
    .send();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接