我正在尝试让 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
可与回调一起使用。您需要等待回调被调用。
您可以通过将此回调转换为 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 ...
}
关于javascript - 下一个JS : async getInitialProps() with AWS S3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60075209/