【问题标题】:nextJS: async getInitialProps() with AWS S3?nextJS:异步 getInitialProps() 与 AWS S3?
【发布时间】:2020-05-21 07:59:34
【问题描述】:

我正在尝试在 nextJS 项目中的异步 getInitialProps() 函数中运行 s3.getObject(),但我不知道如何将结果准备好作为对象返回(getInitialProps() 和 nextJS 的 SSR 需要它才能正常工作)。

代码如下:

static async getInitialProps({ query }) {
  const AWS = require('aws-sdk');
  const s3 = new AWS.S3({
    credentials: {
      accessKeyId: KEY
      secretAccessKey: KEY
    }
  });

  // The id from the route (e.g. /img/abc123987)
  let filename = query.id;

  const params = {
    Bucket: BUCKETNAME
    Key: KEYDEFAULTS + '/' + filename
  };

  const res = await s3.getObject(params, (err, data) => {
    if (err) throw err;
    let imgData = 'data:image/jpeg;base64,' + data.Body.toString('base64');
    return imgData;
  });

  return ...
}

这个想法是从 S3 获取图像并将其作为 base64 代码返回(只是为了清除问题)。

【问题讨论】:

    标签: javascript node.js reactjs amazon-s3 next.js


    【解决方案1】:

    从您的代码中,s3.getObject 与回调一起使用。您需要等待回调被调用。

    您可以通过将此回调转换为promise来实现。

    
    static async getInitialProps({ query }) {
      const AWS = require('aws-sdk');
      const s3 = new AWS.S3({
        credentials: {
          accessKeyId: KEY
          secretAccessKey: KEY
        }
      });
    
      // The id from the route (e.g. /img/abc123987)
      let filename = query.id;
    
      const params = {
        Bucket: BUCKETNAME
        Key: KEYDEFAULTS + '/' + filename
      };
    
      const res = await new Promise((resolve, reject) => {
        s3.getObject(params, (err, data) => {
          if (err) reject(err);
          let imgData = 'data:image/jpeg;base64,' + data.Body.toString('base64');
          resolve(imgData);
        });
      });
    
    
      return ...
    }
    

    【讨论】:

      猜你喜欢
      • 2016-12-29
      • 2021-09-15
      • 2017-01-06
      • 1970-01-01
      • 2019-09-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-12
      • 1970-01-01
      相关资源
      最近更新 更多