Cloud Resume Challenge – Visitor Counter Part 4, JavaScript

Now that we have our API up and running, it’s time to add some JavaScript code to the front-end to call the API and display the results as a visitor count.

JavaScript has long been the language used to add functionality and interactivity to otherwise static webpages. Historically, JavaScript has usually run in-browser at the client side (which is what I’ll be doing here) but it’s been having a second renaissance, as a back-end language, due to the popular Node.js runtime environment. JavaScript’s first renaissance began back in the mid-00’s with the advent of a set of techniques known as Asynchronous JavaScript and XML, or Ajax.

Ajax allowed for JavaScript to make calls to remote servers, which would respond with data in the XML format. The asynchronous aspect meant that such calls could be made whilst allowing other processes (ie the loading and display of content, and the running of any other scripts) to continue, without requiring the call to complete first. Whilst data is now more usually returned in the JSON format, the use of asynchronous JavaScript to make API calls is still extremely prevalent.

Modern JavaScript includes the Fetch API, an interface that offers predefined objects and methods, specifically for requesting resources from a server. It returns a “promise”; a response to a call that will either eventually be the requested data or the reason that the call failed.

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:

<script src="js/counter.js"></script>

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…