API响应
body: ReadableStream
bodyUsed: true
headers: Headers
__proto__: Headers
ok: false
redirected: false
status: 502
statusText: ""
type: "cors"
url: "correct-url"
__proto__: Response
但是Lambda的日志报告它正在返回有效的响应:
2019-05-16T20:40:54.113Z some-id-snipped { statusCode: 200,
correct headers and body...
Lambda结尾代码:
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if (err) {
localLogger.log(err);
callback(null, failure(err, localLogger));
} else {
const response = { url: data, fileName };
callback(null, success(response, localLogger));
}
});
成功方法:
export function success(body, logger = console) {
const response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true
},
body: JSON.stringify(body)
};
logger.log(response);
return response;
}
无服务器上传定义:
getUploadUrl:
handler: src/resourceImages.getUploadUrl
events:
- http:
path: resourceImages/getUploadUrl
method: get
cors: true
authorizer:
arn: ${self:provider.environment.USER_POOL_ARN}
请注意,浏览器首先发送一个OPTIONS请求,该请求返回200,然后发送GET,该请求返回502。
答案 0 :(得分:0)
s3.getSignedUrl直到lambda完成解析后才解析,因此回调从未解析。我需要将s3.getSignedUrl包装在一个使其工作的承诺中:
function getSignedUrlPromise(s3Params) {
const s3 = new AWS.S3({ signatureVersion: 'v4', });
return new Promise(function(resolve, reject) {
s3.getSignedUrl('putObject', s3Params, (err, data) => {
if (err) {
reject(err);
} else {
resolve(data);
}
});
})
}
await getSignedUrlPromise(s3Params).then((response) => {
const data = { url: response, fileName };
callback(null, success(data, localLogger));
}).catch((err) => {
localLogger.log(err);
callback(null, failure(err, localLogger));
});