2

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}

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

4

1 回答 1

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));
});
于 2019-05-17T16:33:34.247 回答