我正在尝试在我的网站上设置联系表单,我觉得已经很接近了,但源地址值出现了一些问题。我以 URL 编码而不是多部分的形式传递数据,因为我只需要一些文本。
联系表:
<form id='contact-form'>
<label for='replyTo'>Email</label>
<input name='replyTo' id='replyTo' type='email' autocomplete='email' required>
<label for='subject'>Subject</label>
<input name='subject' id='subject' required>
<label for='message'>Message</label>
<textarea name='message' id='message' autocapitalize='sentences' maxlength='3000' minlength='10' placeholder='Comment text' rows='3' spellcheck='true' required></textarea>
<button id='submit-btn' type='button'>Send</button>
</form>
Javascript 处理程序:
const submitBtn = document.getElementById('submit-btn'),
htmlForm = document.getElementById('contact-form'), //contact form
endpoint = "https://xxxxxxxxxx.execute-api.us-west-2.amazonaws.com/Email";
submitBtn.addEventListener('click', () => {
const formData = new FormData(htmlForm),
urlEncodedData = new URLSearchParams();
for (const pair of formData.entries()) {
urlEncodedData.append(pair[0], pair[1]);
}
htmlForm.requestSubmit();
fetch(endpoint, {
method: "post",
body: urlEncodedData,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(response => {
if (response.ok) {
resetForm();
} else {
throw new Error('HTTP error. Status: ${response.status}');
}
});
});
htmlForm.addEventListener('submit', (event) => {
event.preventDefault(); // prevents submitting to self (page)
});
Lambda 函数:
const AWS = require('aws-sdk'),
ses = new AWS.SES(),
querystring = require('querystring');
exports.handler = async (event) => {
const formData = querystring.parse(event.body),
message = formData.message,
replyTo = formData.replyTo,
subject = formData.subject,
emailParams = {
Source: "form@<verified_domain_tld_here>",
Destination: {
ToAddresses: ["<my actual email address>"]
},
Message: {
Subject: {
Data: `${subject}`
},
Body: {
Text: {
Data: `${message}`
}
}
},
ReplyToAddresses: [`${replyTo}`]
};
try {
await ses.sendEmail(emailParams).promise();
console.log(successMessage);
return {
statusCode: 200,
body: JSON.stringify({ message: successMessage })
};
} catch (err) {
console.log(err);
return {
statusCode: err.statusCode || 500,
body: JSON.stringify({ message: err.message || errorMessage })
};
}
};
答案1
事实证明,数据是通过这种方式编码成 Base64 的:const formData = new FormData(htmlForm)
这意味着我必须在服务器端对其进行解码,然后才能正确解析正文。