我正在尝试让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代码返回(只是为了澄清问题)。
发布于 2020-02-06 01:01:49
在您的代码中,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 ...
}
https://stackoverflow.com/questions/60075209
复制相似问题