[英]nextJS: async getInitialProps() with AWS S3?
我正在尝试让 s3.getObject() 在 nextJS 项目中的异步 getInitialProps() 函数内运行,但我不能因为喜欢它弄清楚如何获得准备好的结果它们可以作为一个返回对象(这是 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 代码返回(只是为了清除问题)。
从您的代码中, s3.getObject
与回调一起使用。 您需要等待回调被调用。
您可以通过将此回调转换为承诺来实现它。
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 ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.