Here, I’m using fetch() within my function to make a call to my API Gateway (adding my API key, stored in a separate config file, to the URL) using the POST method specified in my backend app:
I’m then “chaining” a further two functions to the original fetch() call, using the “then” keyword. This passes the returned value of each step along the chain, until the counter() function resolves by returning the value of the last step. Taken in turn:
- The fetch call returns a Response object from the initial call to the API
- The second step “reads” that response and returns a JSON object to the final step
- The final step looks for a div element in my HTML code called “counter” (which I’ll create in a sec), and adds a <h4> element to it with the text “You are visitor number: ” and concatenates the value passed in the second step
All that’s then required is to create a div with the ID “counter” in the place in my index.html file that I want the counter to display, and to add a link to the script file in <head> area, like so:
And it works!
So with the visitor counter up and running, I now have the resume site with all the required functionality. But I’m not done yet! The whole next chunk of the challenge concerns setting up a CI/CD pipeline, so next time I’ll start with one of the core elements of that process, testing…