I am trying to work out how to embed an API call response into my index.html
file in order to update a website counter using JavaScript.
I have tried multiple blogs and YouTube tutorials but as I'm not experienced with JS I am really struggling.
Here is my API:
https://b9hsa93hif.execute-api.eu-west-2.amazonaws.com/Prod/hello/
Here is my attempted script.js
file:
const countEl = document.getElementById('count');
updateVisitCount();
function updateVisitCount() {
fetch('https://b9hsa93hif.execute-api.eu-west-2.amazonaws.com/Prod/hello/')
.then(res => res.json())
.then(res => {
countEl.innerHTML = res.value;
})
}
As my API updates automatically each time the page is refreshed, I presume I do not need the JavaScript function itself to count - but I don't know how to rewrite it correctly.
Here is the snippet from my attempted index.html
file:
</div>
<p>This page was viewed</p>
<h1 id="count"></h1>
<p>times</p>
I would like my static webpage to display This page was viewed [return result of API call] times
.
Thanks in advance!
--UPDATE--
I have managed to resolve this, thanks for the contributions @Barmar as they steered me in the right direction, and updating the res.value
to res.clicks
was an essential step.
However, the main issue was the fact that my API is linked to API Gateway and a Lambda function, and I was missing some key code in there. I realised this when trying to enable CORS on the API Gateway resource, and in searching for help I found this SO thread. One of the comments in there had the correct code to include in the Lambda function (I've marked it between >>> <<<):
return {
'statusCode': 200,
>>>'headers': {
"Access-Control-Allow-Origin": "*"
},<<<
'body': json.dumps({'clicks': int(ddbResponse['Attributes']['clicks'])})
When I updated that in my Lambda function, and refreshed the website based on my updated index.html
file, it worked correctly.
Thanks again everyone!