Estoy creando una aplicación con un formulario web que cuando el usuario hace clic en "enviar", los datos se agregan a una tabla de DynamoDB.
El código HTML de mi formulario web incluye una API (creada con API Gateway) que activa una función Lambda que debe analizar los datos y colocarlos en DynamoDB. Sin embargo, recibo un Unexpected token Z in JSON at position 0error cuando envío el formulario web.
Aquí está mi código HTML:
<!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>
Aquí está mi función Lambda:
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
};
};
Cualquier ayuda para resolver este error sería muy apreciada.
Solución del problema
Los formularios no envían datos en formato JSON. Los formularios envían application/x-www-form-urlencodetipo de contenido. Puede usar el objeto URLSearchParams para trabajar con los datos del formulario.
No hay comentarios:
Publicar un comentario