'Submitting HTTP request from HTML to AWS API gateway
I have a HTML form with a button which allows me to send HTTP requests in "text/plain" or "application/x-www-form-urlencoded" format.
text/plain:
stateMachineArn=arn:aws:states:us-east-1:0111111165:stateMachine:MyStateMachine
name=ExecutionName
first_name=test
last_name=test2
application/x-www-form-urlencoded:
stateMachineArn=arn:aws:states:us-east-1:0111111165:stateMachine:MyStateMachine&name=ExecutionName&first_name=test&last_name=test2
But AWS API gateway receives only JSON format by default ("input" has to be escaped)
{
"input": "{\"first_name\" : \"test\",\"last_name\" : \"test2\"}",
"name": "ExecutionName",
"stateMachineArn": "arn:aws:states:us-east-1:0111111165:stateMachine:MyStateMachine"
}
How can I convert either formats to the above JSON?
Solution 1:[1]
If you have a form like this:
<form>
<input type="stateMachineArn" name="stateMachineArn" id="stateMachineArn" />
<input type="name" name="name" id="name" />
<label for="first_name">First name</label>
<input type="first_name" name="first_name" id="first_name" />
<label for="last_name">Last name</label>
<input type="last_name" name="last_name" id="last_name" />
<button type="submit">Submit</button>
</form>
You can handle submissions in js like this and log the response like you did - don´t know if that´s what you are doing:
function handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
const value = Object.fromEntries(data.entries());
console.log({ value });
}
const form = document.querySelector('form');
form.addEventListener('submit', handleSubmit);
At this point if you want to convert data object to json before sending it somewhere or just to log it, have you tried this?
console.log(JSON.stringify(data));
Or this?
console.log(JSON.stringify(value ));
EDIT
To send the request:
$.ajax({
type: "POST",
url: "/webservices/PodcastService.asmx/CreateMarkers",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
error: function(errMsg) {
alert(errMsg);
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
