使用 Express 从 AWS S3 存储桶提供整个 React CRA

Serve Entire React CRA from AWS S3 bucket using Express

我基本上是在尝试使用 express 作为一种反向代理。我的最终目标是为不同的用户提供不同的 React CRA 包。现在虽然我只是在进行概念验证,看看是否有可能做到这一点。

TLDR 目标:

这是我在 express 中使用的代码:

app.get('/*', function (req, res) {
  const bucketParams = {
    Bucket: 'some-dumb-bucket',
    Key: 'cra/index.html'
  };

  s3.getObject(bucketParams)
  .on('httpHeaders', function (statusCode, headers) {
    res.set('Content-Length', headers['content-length']);
    res.set('Content-Type', headers['content-type']);
    res.set('Last-Modified', headers['last-modified']);
    this.response.httpResponse.createUnbufferedStream()
      .pipe(res);
    })
    .send();
})

我遇到的问题是我返回的所有内容都是错误的headers。当我进入 s3 并查看元数据时,它具有正确的 headers 那么为什么它获取所有 headers 作为“text/html”?

我知道我做错了什么了!它正在循环并抓住相同的 index.html headers。修复:

app.get('/*', function (req, res) {
  const bucketParams = {
    Bucket: 'some-dumb-bucket',
    Key: 'auth/index.html'
  };

  if (req.url && req.url !== '/') {
    bucketParams.Key = `auth${req.url}`;
  } else
   bucketParams.Key = `auth/index.html`;

  // send the assets over from s3
  s3.getObject(bucketParams)
    .on('httpHeaders', function (statusCode, headers) {
      res.set('Content-Length', headers['content-length']);
      res.set('Content-Type', headers['content-type']);
      res.set('Last-Modified', headers['last-modified']);
      res.set('ETag', headers['etag']);
      this.response.httpResponse.createUnbufferedStream()
        .pipe(res);
    })
    .send();
});

代码可能更简洁一些,但 PoC 可以正常工作。