-4

I've got the following JS which is attempting to return a value from an AWS API Gateway:

 <script>
        fetch("https://myapi/get")
        .then(response => response.json())
        .then(data => {
        document.getElementById("website-counter").innerHTML = data.body
        });
 </script>

The API GW triggers a lambda function to get a value from a DynamoDB table. Im attempting to display the retuned value by

<p>
   CV Website Views: <span id="website-counter"></span><br/>
                
</p>

However, the "website-counter" returns an undefined value, not the required DB value.

Also, Ive set the CORS headers in the Lambda function itself. If i access the direct link to the API from AWS console, i get the retuned value from dynamodb as expected.

sjb_1981
  • 13
  • 1
  • Make sure you've put your script tag before you close the `body` tag. (towards the end of file) – AdityaParab Aug 17 '22 at 13:18
  • The script tag is already before the closing body tag, thanks – sjb_1981 Aug 17 '22 at 13:42
  • There's not enough information in the question to determine why `data.body` is undefined. You haven't provided the code for the API, nor a log of what `data` actually is. – Quentin Aug 17 '22 at 15:32

1 Answers1

0

This post resolved the issue for me: ES6 fetch function returns undefined

This is now working fine:

     <script type ="text/javascript">
            function visitcount() {
                return fetch("https://myapi/get").then(function(response) {
                return response.json();
                }).then(function(json) {
                    return json;
                });
                                }

                visitcount().then(function(result) {
                document.getElementById("website-counter").innerHTML = result
                console.log(result);
                });
        
    </script>
sjb_1981
  • 13
  • 1
  • This has a *lot* of changes which are completely redundant. It looks like the root cause of your problem is that your API *doesn't* return a JSON text with a property called `body` on it. (That is the only significant change between this and your original code I can see) That's the sort of trivial error that isn't generally useful, so you'd be better off just deleting the question instead. – Quentin Aug 17 '22 at 15:31