How can I serve static web site from s3 through node expressjs?

巧了我就是萌 提交于 2020-01-01 09:56:28

问题


currently I use app.use(express.static('public')) and my files located in the public folder of my node js express app and its working good. However, I would like to store those files (index.html, etc) in my s3 bucket (so multiple apps can use this website). I tried

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

with no success...


回答1:


I wouldn't reinvent the wheel. There's a reasonably recent and well documented middleware module for this on npm

From the docs:

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:


I wanted /foo to match a /foo.html on a different s3 bucket. I used the following to do so:

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();
});


来源:https://stackoverflow.com/questions/40262009/how-can-i-serve-static-web-site-from-s3-through-node-expressjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!