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 count
my 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!!!!
2
Answers
Have you checked to see in the browser dev tools what the response is from your URL? It should show up as a network request and you can see the actual data returned from your function.
That being said it looks like you’re returning
Casing matters here so your code to update should actually be
not
Casing matters in objects, and your casing seems wrong. In your lambda, you return this response:
But in your JS code, you use
count
with a lower casec
:Change the casing of one or the other to match, for example your JS to this:
Furthermore, you don’t need to issue the GetItem request, just work with the UpdateItem:
This will save you both on capacity costs but more importantly, latency.