I am developing a IoT project in which i use an ESP32 to connect to the AWS MQTT Broker, i get some readings (is a smart parking) and generate some simple DynamoDB tables, I want to deploy an API to get some CRUD Operations over my Users Table.
This is the Lambda Code for it.
import boto3
import json
def lambda_handler(event, context):
try:
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Users')
# Ensure required fields are present
if 'ID' not in event or 'name' not in event or 'credits' not in event:
return {
'statusCode': 400,
'body': json.dumps('Missing required fields')
}
item = {
'ID': event['ID'],
'name': event['name'],
'credits': int(event['credits']),
'last_in': event.get('last_in', ''),
'last_out': event.get('last_out', ''),
'is_in': event.get('is_in', False)
}
table.put_item(Item=item)
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type'
},
'body': json.dumps('User created successfully')
}
except Exception as e:
return {
'statusCode': 500,
'body': json.dumps(f'Error: {str(e)}')
}
And then i created a POST Method with CORS Activated METHODS
POST METHOD
Whenever i try to send some data from a localhost webpage i get a CORS ERROR
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create User</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">
<h2>Create User</h2>
<form id="createForm">
<div class="form-group">
<label for="createID">User ID</label>
<input type="text" class="form-control" id="createID" placeholder="Enter user ID" required>
</div>
<div class="form-group">
<label for="createName">Name</label>
<input type="text" class="form-control" id="createName" placeholder="Enter name" required>
</div>
<div class="form-group">
<label for="createCredits">Credits</label>
<input type="number" class="form-control" id="createCredits" placeholder="Enter credits" required>
</div>
<button type="submit" class="btn btn-primary">Create</button>
</form>
</div>
<script>
const apiUrl = 'myurl';
document.getElementById('createForm').onsubmit = async (e) => {
e.preventDefault();
const id = document.getElementById('createID').value;
const name = document.getElementById('createName').value;
const credits = document.getElementById('createCredits').value;
await fetch(`${apiUrl}/users`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ ID: id, name, credits: parseInt(credits) })
})
.then(response => response.json())
.then(data => alert(data.body))
.catch(error => console.error('Error:', error));
};
</script>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
Thats the HTML
My error states
Ensure CORS response header values are valid
A cross-origin resource sharing (CORS) request was blocked because of invalid or missing response headers of the request or the associated preflight request .
To fix this issue, ensure the response to the CORS request and/or the associated preflight request are not missing headers and use valid header values.
Note that if an opaque response is sufficient, the request’s mode can be set to no-cors to fetch the resource with CORS disabled; that way CORS headers are not required but the response content is inaccessible (opaque).
1 request
Request Status Preflight Request (if problematic) Header Problem Invalid Value (if available)
users blocked Access-Control-Allow-Origin Missing Header
I tried setting up the Headers thingy in both the Lambda Code and the User Route (CORS ACTIVATED)
But still get the same error
Diego Párraga V. is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.