nextJS:异步 getInitialProps() 与 AWS S3?
nextJS: async getInitialProps() with AWS S3?
我正在尝试在 nextJS 项目的异步 getInitialProps() 函数中获取一个 s3.getObject() 运行,但我不能因为喜欢它而弄清楚如何得到准备好的结果,它们可以 return 作为一个对象编辑(这是 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 中获取图像并将其 return 作为 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 ...
}
我正在尝试在 nextJS 项目的异步 getInitialProps() 函数中获取一个 s3.getObject() 运行,但我不能因为喜欢它而弄清楚如何得到准备好的结果,它们可以 return 作为一个对象编辑(这是 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 中获取图像并将其 return 作为 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 ...
}