Api网关304使用Last-Modified标头进行响应

时间:2016-07-19 10:34:50

标签: aws-lambda aws-api-gateway serverless-framework

我想用Last-Modified标头响应304响应。

首先我使用错误响应来实现。

Handler.js

module.exports.handler = function(event, context, cb) {
  const UpdateDate = new Date();
  return cb("304 Not Modified", {
    "Last-Modified": UpdateDate,
    "body":{
      "message": {}
    }
  });
};

端点中的s-function.json

"responses": {
    "304 Not Modified.*": {
      "statusCode": "304",
      "responseParameters": {
        "method.response.header.Last-Modified": "integration.response.body.Last-Modified"
      },
      "responseModels": {
        "application/json;charset=UTF-8": "Empty"
      },
      "responseTemplates": {
        "application/json;charset=UTF-8": "$input.json('$.body')"
      }
    },
    "default": {
      "statusCode": "200",
      "responseParameters": {
        "method.response.header.Cache-Control": "'public, max-age=86400'",
        "method.response.header.Last-Modified": "integration.response.body.Last-Modified"
      },
      "responseModels": {
        "application/json;charset=UTF-8": "Empty"
      },
      "responseTemplates": {
        "application/json;charset=UTF-8": "$input.json('$.body')"

      }
    }
}

但是,我在Lambda doc上找到了它。

  

如果提供错误,则忽略回调参数。

所以,这不起作用。

是否有任何解决方案来响应带有标题的304响应?

更新:

是否可以在s-function中返回Error对象并映射响应304?下面的代码无法映射到304。

S-funtion.json

"responses": {
    ".*304 Not Modified.*": {
      "statusCode": "304",
      "responseParameters": {
        "method.response.header.Cache-Control": "'public, max-age=86400'",
        "method.response.header.Last-Modified": "integration.response.body.errorMessage.Last-Modified"
      }
}

Handler.js

return cb({
  "status" : "304 Not Modified",
  "Last-Modified": UpdateDate
), null);

我也试试这个。它可以映射到304但是头文件无法获得“integration.response.body.errorMessage.Last-Modified”

return cb(JSON.stringify({
  "status" : "304 Not Modified",
  "Last-Modified": UpdateDate
}), null);

我尝试使用$ util.parseJson,但没有使用responseParameter。

  

指定的映射表达式无效:$ util.parseJson($ input.path('$ .errorMessage'))。Last-Modified

 "responseParameters": {
        "method.response.header.Cache-Control": "'public, max-age=86400'",
        "method.response.header.Last-Modified": "$util.parseJson($input.path('$.errorMessage')).Last-Modified"
  },

1 个答案:

答案 0 :(得分:2)

要在API中返回状态304,您需要从Lambda函数中抛出错误。可以返回" Last-Modified"来自Lambda函数的错误消息中的值以及路由到" Last-Modified" API响应中的标头。

有关详细信息,请查看选项2 here

谢谢, 莱恩