node.js AWS lambda api 网关错误“格式错误的 Lambda 代理响应”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43708017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AWS lambda api gateway error "Malformed Lambda proxy response"
提问by jjbskir
I am trying to set up a hello world example with AWS lambda and serving it through api gateway. I clicked the "Create a Lambda Function", which set up the api gatway and selected the Blank Function option. I added the lambda function found on AWS gateway getting started guide:
我正在尝试使用 AWS lambda 设置一个 hello world 示例并通过 api 网关为其提供服务。我单击了“创建 Lambda 函数”,它设置了 api 网关并选择了空白函数选项。我添加了AWS 网关入门指南中的 lambda 函数:
exports.handler = function(event, context, callback) {
callback(null, {"Hello":"World"}); // SUCCESS with message
};
The issue is that when I make a GET request to it, it's returning back a 502 response { "message": "Internal server error" }. And the logs say "Execution failed due to configuration error: Malformed Lambda proxy response".
问题是,当我向它发出 GET 请求时,它会返回 502 响应{ "message": "Internal server error" }。并且日志显示“由于配置错误执行失败:格式错误的 Lambda 代理响应”。
回答by Ka Hou Ieong
Usually, when you see Malformed Lambda proxy response, it means your response from your Lambda function doesn't match the format API Gateway is expecting, like this
通常,当您看到 时Malformed Lambda proxy response,这意味着您的 Lambda 函数的响应与 API Gateway 期望的格式不匹配,如下所示
{
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "..."
}
If you are not using Lambda proxy integration, you can login to API Gateway console and uncheck the Lambda proxy integration checkbox.
如果您没有使用 Lambda 代理集成,您可以登录 API Gateway 控制台并取消选中 Lambda 代理集成复选框。
Also, if you are seeing intermittent Malformed Lambda proxy response, it might mean the request to your Lambda function has been throttled by Lambda, and you need to request a concurrent execution limit increase on the Lambda function.
此外,如果您看到 间歇性 Malformed Lambda proxy response,则可能意味着对您的 Lambda 函数的请求已被 Lambda 限制,您需要请求增加 Lambda 函数的并发执行限制。
回答by selftaught91
If lambda is used as a proxy then the response format should be
如果 lambda 用作代理,则响应格式应为
{
"isBase64Encoded": true|false,
"statusCode": httpStatusCode,
"headers": { "headerName": "headerValue", ... },
"body": "..."
}
Note : The body should be stringified
注意:正文应该是字符串化的
回答by Mrk Fldig
Yeah so I think this is because you're not actually returning a proper http response there which is why you're getting the error.
是的,所以我认为这是因为您实际上并没有在那里返回正确的 http 响应,这就是您收到错误的原因。
personally I use a set of functions like so:
我个人使用一组像这样的函数:
module.exports = {
success: (result) => {
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify(result),
}
},
internalServerError: (msg) => {
return {
statusCode: 500,
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true // Required for cookies, authorization headers with HTTPS
},
body: JSON.stringify({
statusCode: 500,
error: 'Internal Server Error',
internalError: JSON.stringify(msg),
}),
}
}
} // add more responses here.
Then you simply do:
然后您只需执行以下操作:
var responder = require('responder')
// some code
callback(null, responder.success({ message: 'hello world'}))
回答by Jonathan
From the AWS docs
来自AWS 文档
In a Lambda function in Node.js, To return a successful response, call callback(null, {"statusCode": 200, "body": "results"}). To throw an exception, call callback(new Error('internal server error')). For a client-side error, e.g., a required parameter is missing, you can call callback(null, {"statusCode": 400, "body": "Missing parameters of ..."}) to return the error without throwing an exception.
在 Node.js 中的 Lambda 函数中,要返回成功的响应,请调用 callback(null, {"statusCode": 200, "body": "results"})。要抛出异常,请调用 callback(new Error('internal server error'))。对于客户端错误,例如缺少必需的参数,您可以调用 callback(null, {"statusCode": 400, "body": "Missing parameters of ..."}) 返回错误而不抛出例外。
回答by Ciryon
For anyone else who struggles when the response appears valid. This does not work:
对于在响应似乎有效时挣扎的其他任何人。这不起作用:
callback(null,JSON.stringify( {
isBase64Encoded: false,
statusCode: 200,
headers: { 'headerName': 'headerValue' },
body: 'hello world'
})
but this does:
但这确实:
callback(null,JSON.stringify( {
'isBase64Encoded': false,
'statusCode': 200,
'headers': { 'headerName': 'headerValue' },
'body': 'hello world'
})
Also, it appears that no extra keys are allowed to be present on the response object.
此外,似乎不允许在响应对象上存在额外的键。
回答by Kohei Mikami
If you're using Go with https://github.com/aws/aws-lambda-go, you have to use events.APIGatewayProxyResponse.
如果您将 Go 与https://github.com/aws/aws-lambda-go一起使用,则必须使用events.APIGatewayProxyResponse.
func hello(ctx context.Context, event ImageEditorEvent) (events.APIGatewayProxyResponse, error) {
return events.APIGatewayProxyResponse{
IsBase64Encoded: false,
StatusCode: 200,
Headers: headers,
Body: body,
}, nil
}
回答by Long Nguyen
I've tried all of above suggestion but it doesn't work while bodyvalue is not String
我已经尝试了上述所有建议,但它不起作用,而body价值不是String
return {
statusCode: 200,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify({
success: true
}),
isBase64Encoded: false
};
回答by Miguel
A very very special case, if you pass the headers directly there is a chance you have this header:
一个非常特殊的情况,如果您直接传递标头,则有可能拥有此标头:
"set-cookie": [ "........" ]
"set-cookie": [ "........" ]
But Amazon needs this:
但亚马逊需要这个:
"set-cookie": "[ \\"........\\" ]"
"set-cookie": "[ \\"........\\" ]"
回答by Nigrimmist
Just a piece of code for .net coreand C#:
只是一段.net core和C#的代码:
using Amazon.Lambda.APIGatewayEvents;
...
var response = new APIGatewayProxyResponse
{
StatusCode = (int)HttpStatusCode.OK,
Body = JsonConvert.SerializeObject(new { msg = "Welcome to Belarus! :)" }),
Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
};
return response;
Response from lambda will be :
来自 lambda 的响应将是:
{"statusCode":200,"headers":{"Content-Type":"application/json"},"multiValueHeaders":null,"body":"{\"msg\":\"Welcome to Belarus! :)\"}","isBase64Encoded":false}
Response from api gateway will be :
来自 api 网关的响应将是:
{"msg":"Welcome to Belarus! :)"}
回答by parsley72
For Python3:
对于 Python3:
import json
def lambda_handler(event, context):
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'success': True
}),
"isBase64Encoded": False
}
Note the bodyisn't required to be set, it can just be empty:
注意body不需要设置,它可以是空的:
'body': ''

