我已经从教程中复制了一些代码,该教程将表单内容发送到API。该API是在AWS上设置的,如果我使用Postman发送一些JSON,该API可以正常工作。但是,JavaScript无法正常工作。当我点击表单上的提交按钮时,sendDataToLambda函数未执行。如果我在提交按钮上添加onClick =“ sendDataToLambda()”,则该函数将触发(但随后在e.preventDefault()行上失败,这是预期的行为)。
我已经检查了表单ID是否正确,并且侦听器设置正确,并且找不到错误。 我宁愿不使用jQuery。
<body>
<div class=container>
<h1>Notes</h1>
<form id="note-form" style="margin-top:50px;">
<input type="text" id="subject" placeholder="Enter subject here…" class="form-control" /><br/>
<textarea id="body" rows="3" placeholder="Enter body here…" class="form-control"></textarea><br/>
<button type="button" class="btn btn-lg">Submit</button>
</form>
</div>
<script type="text/javascript">
// Adds an event listener to our form. When the form is submitted, it will send data to our Lambda function, which in turn, will send us an email.
document.getElementById('note-form').addEventListener('submit', sendDataToLambda);
// Now for the good stuff. This is the function that will send our data to AWS.
function sendDataToLambda(e) {
console.log('Submit clicked')
e.preventDefault();
// Gets the values of each field in our form. This is the data we'll send to our Lambda function.
var formSubject = document.getElementById('subject').value;
var formBody = document.getElementById('body').value;
// This is the endpoint we created in our API Gateway. This is where we make our POST request, which calls our Lambda function.
var endpoint = 'https://################';
// Remember those form values we just grabbed? We're going to put them into an object here.
var body = {
subject: formSubject,
body: formBody
}
// Here, we instantiate our Request. This is a special object used by the Fetch API so it knows where to send data, what data to send, and how to send it.
var lambdaRequest = new Request(endpoint, {
method: 'POST',
// Quick note: 'no-cors' mode is for development on localhost only!
mode: 'no-cors',
body: JSON.stringify(body)
});
// Call the Fetch API to make our request
fetch(lambdaRequest)
// This is where you can handle errors. This is just an example, so we won't cover that.
.then(response => console.log(response))
.catch(err => console.log(err));
}
</script>
</body>
</html>