我正在尝试使用 AWS Lambda、AWS API Gateway、Amazon SNS 和 AWS Dynamodb 构建无服务器联系表单。我有一个网页,将姓名、电子邮件和电话号码作为表单输入。我试图在提交时将这些输入发送到 dynamodb 表。然后,通过 AWS SNS 发送通知。 lambda 函数由 API 网关触发。当我测试 lambda 函数时,我收到 KeyError。提交后,网页上显示“已提交”。我也尝试使用 Postman,结果显示“未找到消息”。
如果有人帮助我纠正这个错误,那将会非常有帮助。
lambda 函数是:
import json
import boto3
import time
s3 = boto3.client('s3')
sns = boto3.client('sns')
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('contactform')
def lambda_handler(event, context):
body = json.loads(event.get('body', '{}'))
idn = body['id']
name = body['name']
email = body['email']
number = body['number']
params = {
'TableName': contactform,
'Item': {'id': {'S': idn}, 'name': {'S': name}, 'email': {'S': email}, 'number': {'S': number}}
}
try:
response = dynamodb.put_item(**params)
print("Success - item added or updated", response)
response = {
'statusCode': 200,
'body': json.dumps(body),
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': '*'
}
}
publish_to_sns(body)
print(f"response from: {event['path']} statusCode: {response['statusCode']} body: {response['body']}")
return response
except Exception as e:
print("Error", str(e))
response = {
'statusCode': 500, # Internal Server Error
'body': json.dumps({'error': 'Internal Server Error'}),
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': '*'
}
}
print(f"Error response - {event['path']} statusCode: {response['statusCode']} body: {response['body']}")
return response
def publish_to_sns(body):
sns_topic_arn = 'arn:aws:sns:ap-south-1:032143978963:contactform'
sns.publish(
TopicArn=sns_topic_arn,
Message=json.dumps(body),
Subject='New Form Submission',
)
html代码是:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact Form</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Contact Submission Forms</h1>
<h2>Please enter your contact details. We will be contacting you in 24 hours of form submission. Thank you!</h2>
<div class="form-message" id="form-message"></div>
<form class = "container" id="contactForm" action="https://g6vsqwxfr2.execute-api.ap-south-1.amazonaws.com/deployform" method="POST">
<div>
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
</div>
<br>
<div>
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
</div>
<br>
<div>
<label for="number">Phone number</label>
<input type="number" id="number" name="number" required>
</div>
<br>
<button id="button" type="submit">Submit</button>
</form>
<script>
var apiGatewayUrl = 'https://g6vsqwxfr2.execute-api.ap-south-1.amazonaws.com/deployform';
document.getElementById('contactForm').addEventListener('submit', function(event) {
event.preventDefault();
var id = genRandomNo();
var form = event.target;
var formData = new FormData(form);
var contact = {
id: id,
name: formData.get('name'),
email: formData.get('email'),
number: formData.get('number')
};
console.log(contact)
var xmlhr = new XMLHttpRequest();
xmlhr.open('POST', apiGatewayUrl, true);
xmlhr.setRequestHeader('Content-Type', 'application/json');
xmlhr.onreadystatechange = function() {
if (xmlhr.readyState === XMLHttpRequest.DONE) {
var messageElement = document.getElementById('form-message');
if (xmlhr.status === 200) {
var response = JSON.parse(xmlhr.responseText);
console.log(response)
messageElement.textContent = response.message;
form.reset();
} else {
messageElement.textContent = 'Submitted :)';
}
}
};
var contactJson = JSON.stringify(contact);
xmlhr.send(contactJson);
console.log(contactJson)
});
function genRandomNo() {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
</script>
</body>
</html>
不幸的是,我无法发表评论。 你能提供回溯,哪一行抛出了 KeyError 吗? # 在我看来,该事件可能已经缺少“正文”,并且当您尝试分配
idn = body['id']
时,您正在尝试访问一个空字典。