AWS Lambda-API 网关“消息":“内部服务器错误"(502错误的网关) [英] AWS Lambda-API gateway "message": "Internal server error" (502 Bad Gateway)

查看:94
本文介绍了AWS Lambda-API 网关“消息":“内部服务器错误"(502错误的网关)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的 AWS Lambda 函数来使用 python 3.6 将两个数字相加.它读取 val1 &val2 json 正文中的值.当我在 lambda 控制台中测试 lambda 函数时,它工作正常.但是,当我使用 POSTMAN 通过 AWS API 网关通过 POST 请求调用 lambda 函数时,它响应消息":内部服务器错误"(502 错误网关).谁能帮我解决这个错误?

I created a simple AWS Lambda function to add two numbers using python 3.6. It reads val1 & val2 values in json body. When I tested lambda function in lambda console it works fine. But when I call lambda function by a POST request through AWS API gateway using POSTMAN, it responses with "message": "Internal server error" (502 Bad Gateway). Can anyone help me with this error?

Lambda 函数

import json
def lambda_handler(event, context):
    # TODO implement
    val1 = int(event['val1'])
    val2 = int(event['val2'])
    val3 = val1 + val2
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(val3)
    }

JSON 正文

{
    "val1": "3",
    "val2": "5"
}

推荐答案

发生此错误是由于事件对象(python 字典)的行为.当您在 lambda 控制台中测试 lambda 函数时,JSON 主体将直接传递给事件对象.但是当您通过 API 网关尝试时,不仅事件对象是请求负载,而且正文属性也被设置为字符串.

This error occurs due to the behaviour of the event object (python dictionary). When you test lambda function in lambda console JSON body will directly passed to the event object. But when you try it through API gateway, not only event object is the request payload but also body attribute is set as a string.

例如,您的 JSON 正文在事件对象中将是这样

For example your JSON body will be like this in event object

body: "{\n    \"val1\": \"3\",\n    \"val2\": \"5\"\n}"

要解决此错误,请尝试使用 json.loads() 方法将正文字符串转换为 json.

To resolve this error try json.loads() method to convert body string to json.

import json
def lambda_handler(event, context):
    # TODO implement
    try:
        event = json.loads(event['body'])
        val1 = int(event['val1'])
        val2 = int(event['val2'])
        val3 = val1 + val2
    except:
        val3 = 'request error'
    return {
        'statusCode': 200,
        'headers': {'Content-Type': 'application/json'},
        'body': json.dumps(val3)
    }

这篇关于AWS Lambda-API 网关“消息":“内部服务器错误"(502错误的网关)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆