从 AWS Lambda 发送自定义状态代码

时间:2021-01-05 12:07:34

标签: amazon-web-services http aws-lambda

我在 AWS 中设置了一个 Lambda@Edge 函数,它检查给定 cookie 的传入请求,如果请求不存在,则拒绝该请求,或者如果它存在,它会修改另一个操作的请求。到目前为止,代码工作正常,如果 cookie 不存在,请求将被“拒绝”,如果存在则通过,但我从 Lambda 得到的响应是 502,这并不适合我正在努力实现。缩写代码如下:

exports.handler = (event, context, callback) => {
  const request = event.Records[0].cf.request;
  const requestHeaders = request.headers;

  const response = event.Records[0].cf.response;

  // Perform cookie check
  const downloadCookie = 'download-cookie=true';
  let downloadCookieFound = false;

  if (requestHeaders.cookie) {    
    for (let i = 0; i < requestHeaders.cookie.length; i++) {
      if (requestHeaders.cookie[i].value.indexOf(downloadCookie) >= 0) {
        downloadCookieFound = true;
        break;
      }   
    }
  }

  // Reject if cookie not present
  if (!downloadCookieFound) callback(null, request);

  // I have tried this as well but it doesn't seem to work
  // if (!downloadCookieFound) callback(null, { statusCode: 403, body: 'Cookie missing' };

  // Perform other operations
  // ...

  //Return modified response
  callback(null, response);
};

如何让 Lambda 返回 403 响应而不是 502:

502 ERROR
The request could not be satisfied.
The Lambda function returned invalid JSON: The JSON output must be an object type. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.

1 个答案:

答案 0 :(得分:0)

在luk2302的帮助下解决了 - 换行:

if (!downloadCookieFound) callback(null, request);

致:

if (!downloadCookieFound) callback(null, { status: '403' });

如果需要,可以将其他信息添加到返回的对象中。