You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修正POST API请求以向Lambda函数传递Customer数据

问题解决:POST请求传递Customer数据到Lambda失败

前端JavaScript代码修改

你的fetch请求存在三个关键问题,导致数据无法正确传递:

  • 直接传递JavaScript对象作为body,需转换为JSON字符串
  • 缺少Content-Type: application/json请求头,后端无法识别数据格式
  • fetch不支持success/error回调,需改用try/catch处理响应和错误

修改后的代码:

async function ExecuteEC2(customer) {
  try {
    const response = await fetch('https://你的API端点地址', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        Customer: customer,
      })
    });

    if (!response.ok) {
      throw new Error(`HTTP错误!状态码:${response.status}`);
    }

    const result = await response.json();
    alert(`请求成功,返回数据:${result.body}`);
  } catch (error) {
    alert(`请求错误:${error.message}`);
  }
}

Lambda函数代码修改

通过API Gateway触发的Lambda,POST请求的原始数据会被放在event['body']字段中(格式为JSON字符串),需先解析才能获取Customer字段:

修改后的Lambda代码:

import time
import json
import boto3
from pprint import pprint 

region = 'eu-west-2'
instance = 'i-ec2'
ec2 = boto3.client('ec2', region_name=region)

def handler(event, context):
    # 解析请求体的JSON字符串
    request_body = json.loads(event['body'])
    customer_name = request_body['Customer']
    
    print(customer_name)

    # 后续EC2/SSM操作代码(按需启用)
    client = boto3.client('ec2')
    ssm = boto3.client('ssm')
    # response = ssm.send_command(
    #     InstanceIds=['i-ec2'],
    #     DocumentName="AWS-RunShellScript",
    #     Parameters={'commands':[
    #     "mkdir create2.txt",
    #     ]},
    # )
    # print(response)
    
    return {
        'statusCode': 200,
        'body': json.dumps(customer_name)
    }

额外注意事项

  • 请将前端fetch的URL替换为实际的API Gateway完整端点(原代码中'https:api'格式不完整)
  • 确保API Gateway已正确配置,将POST请求转发至目标Lambda函数

内容的提问来源于stack exchange,提问作者IAmTazlan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 08:08:52