Wei's
Dev
Journal

Connecting My frontend and backend (testing via local server)

api concept

Image source: Dribbble / Artist: Vucko

Table:

Step 00 | Preparation

  1. After I created my frontend content ( see the article [Creating the frontend of my website with Github Page]), and configuring backend API endpoints ( see the article [Creating backend for my website]), it is time to connect them !

    💡 At the moment, everything will still be tested locally with a local server IP address. The HTML website that is deployed through GitHub Page will only still remain as a pure static frontend website. In the next article I will show how configure an API with your own DNS.

  2. Opening up the JavaScript connected to the HTML file of the web page and adding the following functions step by step, which will allow the web page show all the comments, update a comment, add a comment and delete a comment.

Step 01 | Configuring Base Variables

  1. const url = new URL(location.href); : Creating new URL to interact with the API.
    • Extracting Query Parameters: You can extract query parameters from the URL to send them as part of an API request.
    • API Endpoints: You can use parts of the current URL to construct API endpoints dynamically.
    • URL Components: You can parse and manipulate different components of the URL (e.g., protocol, hostname, pathname) to use in API requests.
  2. const APILINK = 'https://localhost:8000/api/v1/comments'; : The base URL of the API that endpoints will use to interact with data.
  3. const main = document.getElementById("commentsSection"); : Referencing to the placeholder in the web-page where the requested data will be displayed.

Step 02 | Creating the form for collecting the data

  1. const div_new = document.createElement('div'); : The syntax will dynamically create a new web section using HTML div which contains the web-form. The div will be stored in the variable div_new.
  2. innerHTML is the property of div_new, which contains a string parsing a series of HTML elements that forms the comments (or feedback) form.
  3. main.appendChild(div_new) is the step that will add the new created section into the DOM of the main HTML body.

Step 03 | Create Function to Display all the Feedbacks

  1. In general, the function fetches feedback data from an API url endpoint and dynamically creates HTML elements to display those feedbacks on a webpage.
  2. Fetch API Call:
    • fetch(url) initiates an HTTP GET request to the specified URL.
    • The response is then converted to JSON using response.json().
  3. Handling the Fetched Data:
    • The fetched array of feedback data is processed in the .then(function(data){...}) block. console.log(data); logs the fetched data to the console for debugging purposes.
  4. Iterating Over Comments:
    • data.forEach(comment => {...}) iterates over each comment in the fetched data array. For each comment, a new div element (div_card) is created to hold the comment details.
  5. Formatting and Inserting Comment Data:
    • const comment_id = comment._id; extracts the feedback's unique ID in the MongoDB.
    • const formattedDate = formatDate(comment.date); formats the comment's date using a formatDate function (defined later).
    • div_card.innerHTML = ... sets the inner HTML of the div_card with the comment's details, including subject, text, commentator's name, and formatted date.
    • The HTML also includes "Edit" and "Delete" links with onclick handlers to trigger showEmailVerification function (defined later) with appropriate parameters.
  6. Appending to Main Container:
    • main.appendChild(div_card); appends the newly created div_card to a main container element (main), the connected HTML web page in this case.
  7. Error Handling:
    • .catch(error => {...}) handles any errors that occur during the fetch operation.
    • console.error('Error fetching comments:', error); logs the error to the console.
    • alert('Error fetching comments. Please try again.'); displays an alert to the user indicating that there was an error fetching the comments.


Step 04 | Create Function for Feedback Editing Form

  1. This function is designed to enable the editing of a comment on a webpage.
  2. Element Selection:
    • An HTML element is selected by its id using document.getElementById(id) and assigns it to the variable element.
  3. Input IDs Creation:
    • Unique IDs are assigned for the input fields by concatenating the id parameter with specific strings (subject, comment_text, name, email, verify_email).
  4. Inner HTML Update:
    • The function updates the innerHTML of the selected element to include input fields pre-filled with the provided name, email, subject, and comment_text values.
  5. Save Link: It adds a "Save" link that, when clicked, calls the saveComment function (defined later) with the IDs of the input fields and the original id. The edited comment then will be saved.


Step 05 | Create Function to Save the Updated or Newly Added Feedback

  1. The function is designed to save a comment/ feedback to a backend server.
  2. Function Parameters:
    • Inherit the IDs of the HTML input elements nameInputId, emailInputId, subjectInputId, commentInputId defined in the editComment function, from which the function will retrieve values.
    • id: An optional parameter that, if provided, indicates an existing comment to update; otherwise, a new comment will be created.
  3. Retrieve Input Values:
    • The function retrieves the values from the HTML input elements using document.getElementById().value for name, email, subject, and comment_text.
  4. Determine HTTP Method and URL:
    • If id is provided, the HTTP method is set to 'PUT' (for updating an existing comment) and the URL is constructed using the id.
    • If id is not provided, the HTTP method is set to 'POST' (for creating a new comment) and the URL is set to APILINK.
  5. Send HTTP Request:
    • An HTTP request then will be sent to the server using the fetch API.
    • - The request includes:
      • method: Either `'PUT'` or `'POST'`.
      • headers: Specifies the content type as JSON.
      • body: A JSON string containing the name, email, subject, comment_text, and article.
  6. Error Handling:
    • If the response is successful (response.ok), it logs a success message to the console and reloads the page.
    • - If the response is not successful, it logs an error message to the console with the response status text.


Step 06 | Create Function to Delete a Comment

  1. The function deletes a comment by its id.
  2. Fetch API Call:
    • The function uses the fetch API to send an HTTP DELETE request to a specified URL, constructed using a base APILINK and the provided id.
  3. Await Response: As this is an asynchronous function, the await keyword paring with async pauses the function execution until the fetch request completes and returns a response.
  4. Error Handling:
    • The function checks if the response is successful (response.ok).
    • Success Case: If the response is successful, it logs a success message to the console and reloads the page using location.reload(main).
    • Failure Case: If the response is not successful, it logs an error message to the console with the response's status text.

💡 An asynchronous function is a function that operates asynchronously via the async keyword, allowing the use of await within it. This means the function can pause its execution while waiting for a promise to resolve, without blocking the main thread. This is useful for performing tasks like network requests or file I/O, which can take time to complete, without freezing the user interface or other operations.


Step 07 | Create a Simple Verification Function to enhance security

  1. This pair of functions are used to verify a user's email before allowing them to perform actions such as editing or deleting a comment.
  2. showEmailVerification(commentId, action) Function:
    • Get the Element by ID:
      The function takes two parameters: commentId and action. It retrieves the Feedback HTML element with the ID ( commentId defined in the returnComments(url) function) using document.getElementById(commentId).
    • Append HTML for Email Verification:
      It appends a new HTML block which contains an input field for the user to enter their email and a link that triggers the verifyEmail function when clicked.
  3. verifyEmail(commentId, action)
    • Retrieve and Process Input:
      The function takes two parameters: commentId and actionto retrieve the value from the input field with the ID verifyInput-${commentId}.
    • Fetch Comment Data:
      It sends a GET request to API endpoint to fetch the comment data via commentId.
    • Handle Response:
      If the response is successful (response.ok), it parses the response as JSON to get the comment data. It logs a success message to the console.
    • Email Verification:
      1. It compares the stored email (from the fetched comment data) with the input email.
      2. If they match, it performs the action specified by the action parameter:
        1. If action is 'edit', it calls editComment with the comment details.
        2. If action is 'delete', it calls deleteComment with the commentId and input email.
      3. If they do not match, it alerts the user and appends an error message to the HTML element with the ID commentId.
    • Error Handling:
      If the response is not successful, it logs an error message to the console.


Step 08 | Forcing Date Format Shown in the Display From

  1. The function takes the date string stored in the MongoDB collection as input and returns a formatted date string.
  2. Options Object: An options object is created to specify the formatting options for the date.
  3. Date Object: A Date object is created from the input dateString.
  4. Regional Standard Format Enforcing: The toLocaleDateString method is called on the Date object, with 'en-GB' (British English) as the locale and the options object to specify the format.


Step 09 | Calling the function for returning all relevant Data

  1. The syntax adds an event listener to the connected web page that listens for the DOMContentLoaded event.
  2. () => returnComments(APILINK): When the initial HTML document has been completely loaded and parsed, it calls the returnComments function with the API url.


Step 10 | Run the Node.js Engine to activate the api connection for testing the functions


Step 11 | Test through the frontend interface

  1. Filling in the comment form in the webpage to see if the value is returned and displayed below the form. This means the GET and POST API endpoints are working as well as the saveComment function. api concept api concept
  2. You will find the raw data has now showed up in the data collection on MongoDB portal. Making sure you are at the right project, cluster and data collection. api concept
  3. Try to update it to test the verification function and the function associating with the PUT API endpoint. api concept
    1. click “Edit”.
    2. Filling the email that is the same as the one when the comment was made, and then click “Verify”.
    api concept
    1. The form will enter the editable mode if the verification is successful. Clicking “Save ” after the comment has been updated.
    api concept
    1. The comment now had been updated.
  4. Trying to delete it, which will also allow you to test the verification function. api concept
    1. click “Delete”.
    2. Filling the email that is the same as the one when the comment was made, and then click “Verify”.
    api concept
    1. The comment now had been deleted.

💡 Please refer to my GitHub repository to look at the full code.