简体   繁体   English

获取“内部服务器错误”502:错误的网关错误

[英]Getting "Internal Server Error" 502:Bad Gateway Error

I have just started working on AWS.我刚开始在 AWS 上工作。 I am building a system connection between lambda, RDS MYSQL Database and API gateway.我正在 lambda、RDS MYSQL 数据库和 API 网关之间建立系统连接。

Created a lambda function in python which inserts the data into the MYSQL database and configured API gateway with the lambda function. and when I am testing the lambda function within lambda console, everything is working fine. Created a lambda function in python which inserts the data into the MYSQL database and configured API gateway with the lambda function. and when I am testing the lambda function within lambda console, everything is working fine. but when I am trying to call API from postman, it results in "message": "Internal server error" and 502 bad gateway.但是当我试图从 postman 调用 API 时,它会导致“消息”:“内部服务器错误”和 502 错误网关。

import pymysql
import sys
import logging
import json

logger = logging.getLogger()
logger.setLevel(logging.INFO)

try:
    conn = pymysql.connect(
        host='',
        port=int(3306),
        user="",
        passwd="",
        db="")
except:
    logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
    sys.exit()

logger.info("SUCCESS: Connection to RDS mysql instance succeeded")

cursor=conn.cursor()

def lambda_handler(event, context):
    print(event)
    
    http_method = event['httpMethod']
    
    if http_method == "GET":
        Serial_Number = int(event['queryStringParameters']['Serial_Number'])
        platform = int(event['queryStringParameters']['platform'])
        architecture = int(event['queryStringParameters']['architecture'])
        
    elif http_method == "POST":
        body = json.loads(event['body'])
        
        Serial_Number = body['Serial_Number']
        platform = body['platform']
        architecture = body['architecture']
        
    return{
        'statusCode' : 200,
        'headers': {'Content-Type': 'application/json'},
        'body' : json.dumps(Insertion(Serial_Number, platform, architecture)),
        'messageReason' : "Successfully updated Details"
    }
    
def Insertion(Serial_Number, platform, architecture):
    item_count = 0
    
    with conn.cursor() as cur:
        cur.execute("insert into system_data (Serial_Number, platform, architecture) values(%s, %s, %s)", (Serial_Number, platform, architecture))

        conn.commit()
        cur.execute("select * from system_data")
        
        for row in cur:
            item_count += 1
            logger.info(row)
    return "Added %d items to RDS MySQL table" %(item_count)

But when I am trying to call API with postman, I am getting "internal server error" in postman.但是当我试图用 postman 调用 API 时,我在 postman 中收到“内部服务器错误”。

Http status 502 in Api Gateway with Lambda Integration is related to a bad-formatted response from lambda. Api 网关中的 Http 状态 502 与 Lambda 集成与来自 Z945F3FC4495188A763B 的格式错误的响应有关The valid structure of response is described in this guide https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for-lambda-output-format本指南中描述了响应的有效结构https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-proxy-integrations.html#api-gateway-simple-proxy-for- lambda 输出格式

This is why in lambda test console you get a 200 - OK response as it is a valid general json but testing from Api Gateway is not valid as is not the expected structure.这就是为什么在 lambda 测试控制台中您会得到 200 - OK 响应,因为它是有效的通用 json 但从 Api 网关进行的测试不是有效的,因为不是预期的结构。

From your code, the problem is originated due to a non-valid field "messageReason" in response.从您的代码中,问题是由于响应中的无效字段“messageReason”而引起的。 Try removing this field and include it in headers or body尝试删除此字段并将其包含在标题或正文中

502 Bad Gateway Exception, usually for an incompatible output returned from a Lambda proxy integration backend and occasionally for out-of-order invocations due to heavy loads. 502 Bad Gateway Exception,通常是针对从 Lambda 代理集成后端返回的不兼容 output 以及偶尔由于负载过重导致的乱序调用。

I had the same problem because I sent response_body=None.我遇到了同样的问题,因为我发送了 response_body=None。 Then, I created a Dictionary {}, and it worked.然后,我创建了一个字典 {},它起作用了。

  return {
        'statusCode': 200,
        'headers': 
            {
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'OPTIONS,POST'
            },
        'body': json.dumps(response_body)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM