【问题标题】:How can I serve static web site from s3 through node expressjs?如何通过节点 expressjs 从 s3 提供静态网站?
【发布时间】:2017-03-08 19:17:34
【问题描述】:
目前我使用 app.use(express.static('public')) 和我的文件位于我的节点 js express 应用程序的公共文件夹中,并且工作良好。
但是,我想将这些文件(index.html 等)存储在我的 s3 存储桶中(以便多个应用程序可以使用该网站)。
我试过了
app.get('/', function(req, res) {
res.sendfile('link-to-s3-file/index.html');
});
没有成功...
【问题讨论】:
标签:
node.js
amazon-web-services
express
amazon-s3
【解决方案1】:
我不会重新发明轮子。在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'
}));
【解决方案2】:
我希望 /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();
});