'"Unexpected token Z in JSON at position 0" when trying to POST web form data to DynamoDB
I am creating an application with a web form that when the user clicks "submit", the data is added to a DynamoDB table.
My web form's HTML code includes an API (created using API Gateway) which triggers a Lambda function that should parse the data and Put it in DynamoDB. However, I'm getting an Unexpected token Z in JSON at position 0
error when I submit the web form.
Here is my HTML code:
<!DOCTYPE html>
<html lang="en-US">
<body>
<p>Sign-Up Form</p>
<form action="https://XXXXXXXXXX.execute-api.us-east-1.amazonaws.com/Prod/submit" method="post">
<ul>
<li>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" required>
</li>
<li>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name" required>
</li>
<li>
<label for="mail">E-mail:</label>
<input type="email" id="mail" name="user_email" required>
</li>
<li>
<label for="region">Which region are you based in?</label>
<select name="region" id="region" required>
<option value="">--Select--</option>
<option value="emea">EMEA</option>
<option value="amer">AMER</option>
<option value="apj">APJ</option>
</select>
</li>
<li class="button">
<button type="submit">Submit Sign-Up Form</button>
</li>
</ul>
</form>
</body>
</html>
Here is my Lambda function:
const AWS = require("aws-sdk");
const dynamo = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event, context) => {
let body;
let statusCode = 200;
const headers = {
"Content-Type": "application/json"
};
try {
switch (event.routeKey) {
case "POST /items":
let requestJSON = JSON.parse(event.body);
await dynamo
.post({
TableName: "XXXXXX",
Item: {
first_name: requestJSON.first_name,
last_name: requestJSON.last_name,
user_email: requestJSON.user_email,
region: requestJSON.region
}
})
.promise();
body = `Put item ${requestJSON.user_email}`;
break;
default:
throw new Error(`Unsupported route: "${event.routeKey}"`);
}
} catch (err) {
statusCode = 400;
body = err.message;
} finally {
body = JSON.stringify(body);
}
return {
statusCode,
body,
headers
};
};
EDIT
Instead of going through the complication of creating my own API and coding the Lambda function, I followed this great tutorial Forms without servers instead.
Solution 1:[1]
Forms do not send data in JSON format. Forms send application/x-www-form-urlencode
content type. You can use the URLSearchParams object to work with the form data.
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 | Ross Williams |