I'm trying to setup a viewer count for my portfolio, using AWS dynamo DB and AWS lambda with the help of Function URL. the AWS lambda works fine but when it is called by using JavaScript it shows the error "Failed to Fetch" but the Lambda function works, it fetches and update the DynamoDB.
everything works fine my DynamoDB table looks like this ignore the first rowenter image description here my lambda code is this I'm trying to setup a viewer count for my portfolio, using AWS dynamo DB and AWS lambda with the help of Function URL. the AWS lambda works fine but when it is called by using JavaScript it shows the error "Failed to Fetch" but the Lambda function works, it fetches and update the DynamoDB.import json
import boto3
dynamodb = boto3. resource('dynamodb')
ddbTableName = 'Cloud-resume'
table = dynamodb.Table(ddbTableName)
def lambda_handler(event, context):
response = table.get_item(Key= {'id': 'count'})
count = response["Item"]["vistor_count"]
new_count = str(int(count)+1)
response = table.update_item(
Key={'id': 'count'},
UpdateExpression='set vistor_count = :c',
ExpressionAttributeValues={':c':new_count},
ReturnValues='UPDATED_NEW'
)
return {'Count':new_count}
I added a JavaScript code to retrieve the data from DynamoDB using lambda using this code
<script>
fetch('xyz.lambda-url.us-east-1.on.aws/')
.then(response => response.json())
.then((data) => {
document.getElementById('visitor_counter').innerText = data.count
})
</script>
I have created a HTML tag to show the viewer count
Viewer countmy lambda works fine, it shows the output in the URL, I just don't see the viewer count in the portfolio, i have been trying to debug this for hours please help , THANK YOU!!!!
Casing matters in objects, and your casing seems wrong. In your lambda, you return this response:
{'Count':new_count}
But in your JS code, you use count
with a lower case c
:
document.getElementById('visitor_counter').innerText = data.count
Change the casing of one or the other to match, for example your JS to this:
document.getElementById('visitor_counter').innerText = data.Count
Furthermore, you don't need to issue the GetItem request, just work with the UpdateItem:
response = table.update_item(
Key={'id': 'count'},
UpdateExpression='set vistor_count = visitor_count + :c',
ExpressionAttributeValues={':c' : 1},
ReturnValues='UPDATED_NEW'
)
return {'Count':response['Attributes']['visitor_count']}
This will save you both on capacity costs but more importantly, latency.