尽管 Lambda 日志报告成功,但客户端收到 502 错误

Client receiving 502 error despite Lambda logs reporting success

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}

请注意,浏览器首先发送一个 returns 200 的 OPTIONS 请求,然后发送一个 returns 502 的 GET。

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));
});