Home > Back-end >  Fetch API visitor counter
Fetch API visitor counter

Time:07-16

First time poster, long time lurker. I am trying to complete part of the Cloud Resume Challenge, where after creating an AWS API gateway that links a Lambda function, I need to write some Javascript to call the API and return the current visitor count from Lambda function.

I have searched a number of solutions but they dont seem to work for me, I feel I am close.

Here is what I have for the script

          <article>
            <script>
              fetch('https://5cabfxax81.execute-api.ap-southeast-2.amazonaws.com/Prod/')
                  .then((response => response.json()))  
                  .then(data => 
                    console.log(data))
                  .then(response=> {document.getElementById("counter").innerHTML = data.count});                                
            </script>
            <p >You are visitor number <span id="counter">loading...</span></p> 
            <p></p>
          </article>

And this is the error I get Error message

Can anyone push me in the right direction? Am I being super stupid here?

CodePudding user response:

I got it!

            <script>
              fetch('https://5cabfxax81.execute-api.ap-southeast-2.amazonaws.com/Prod/')
                  .then((response => response.json()))  
                  .then((data) => {document.getElementById("counter").innerHTML = data})                                
            </script>
            <p >You are visitor number <span id="counter">loading...</span></p> 
            <p></p>
          </article>

CodePudding user response:

fetch(url, {method:'get'})

You can use that so you don't have to deal with empty data or response

  • Related