Pug template failing to render in browser when attempting to fetch data using a get request from the browser

Currently I'm in the midst of a small project where I need to extract data from a database on a daily basis. Without delving into all the technical details, let's focus on the specific issue at hand.

In my setup, I am utilizing:

  1. Express and Pug on the backend
  2. Fetch API on the frontend.

The browser being used is Chrome

Here is the code snippet from my frontend file - getDates.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Get Dates</title>
    <link rel="stylesheet" href="styles.css">

    <script>
        window.onload = ()=>{
            document.getElementById('confirm').addEventListener('click', sendData)

            function sendData(e){
                e.preventDefault()

                const dates = document.querySelectorAll('input[type=date]')
                let data = {}

                for (date of dates){
                    data[date.name]= date.value
                }

                // using fetch to send get request to server 
                fetch(`/${data.sdate}/${data.edate}`, 
                      { method: 'GET',
                        mode: 'no-cors' } )
                        .catch( err => console.log(err)  )
            }
        }
    </script>

</head>
<body>

    <div class="wrapper">
        <div>Enter Dates</div>
        <form action="">
            <label for="sdate">Start date:</label>
            <input type="date" name="sdate" id="sdate">
            
            <label for="edate">End date:</label>
            <input type="date" name="edate" id="edate">
            <button id="confirm">Confirm</button>
        </form>

    </div>

</body>
</html>

Moving on to the backend side, here is the code snippet from index.js:

const path = require('path');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;

// data received from database 
const data = [
    { date : new Date('2021-04-01'), id : 1, amount: 100, remark : 'test1' },
    { date : new Date('2021-04-05'), id : 2, amount: 100, remark : 'test2' },
    { date : new Date('2021-04-07'), id : 3, amount: 100, remark : 'test3' },
    { date : new Date('2021-04-09'), id : 4, amount: 100, remark : 'test4' },
    { date : new Date('2021-04-10'), id : 5, amount: 100, remark : 'test5' },
    { date : new Date('2021-04-14'), id : 6, amount: 100, remark : 'test6' },
    { date : new Date('2021-04-15'), id : 7, amount: 100, remark : 'test7' },
    { date : new Date('2021-04-18'), id : 8, amount: 100, remark : 'test8' },
    { date : new Date('2021-04-19'), id : 9, amount: 100, remark : 'test9' },
    { date : new Date('2021-04-20'), id : 10, amount: 100, remark : 'test10' }
]


app.use(express.static(__dirname));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

app.get('/', (req, res)=>{
    res.sendFile(__dirname + '/getDates.html')
})


app.get('/:p1/:p2', (req, res)=>{

    // filter data datewise 
    const filtered = data.filter( element =>{
        return element.date >= new Date( `${req.params.p1}` ) && element.date <= new Date( `${req.params.p2}` )
    } )
    

    // prepare data for use with pug template 
    let fData =[]
    fData.push( Object.keys( filtered[0] ).map(x => x.toUpperCase() ) ) 

    for (let line of filtered){
        fData.push( Object.values( line ) )   
    }

    // console.log( fData )  // check data on console -->> upto here it works fine 
    res.render('report', { title: 'Sale data', rows: fData })  // this is not rendered if fetch request is sent 

})

app.listen(port, ()=>  console.log(`Server running on port no: ${port} ...`))

    

Additionally, this is an excerpt from the pug file:

doctype html
html(lang="en")
    head
        meta(charset="UTF-8")
        meta(http-equiv="X-UA-Compatible", content="IE=edge")
        meta(name="viewport", content="width=device-width, initial-scale=1.0")
        title Report
        link(rel="stylesheet" href="../styles.css")
    body 
        .tableDiv 
            div #{title}
            table 
                each row in rows 
                    tr 
                        each col in row 
                            td #{col}        

Last but not least, here is a snippet from the CSS file style.css:

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;

    font: bold 12px arial;  /* short-cut ->> weight style size family */
}

.wrapper {
    margin: 5px;
    background-color: aliceblue;
    padding: 10px 30px;
    display: inline-block;
    border: 1px solid black;
    border-radius: 5px;
}

.wrapper div {
    border-bottom: 1px solid black;
    display: inline-block;
    margin-bottom: 5px;
}

.wrapper form label {
    margin-top: 10px;
}

.wrapper form label, .wrapper form input {
    display:block;
}

.wrapper form button {
    margin-top: 10px;
    padding: 5px 15px;
}

.tableDiv {
    margin: 10px;
    padding: 10px;
    display: inline-block;
}

.tableDiv div {
    padding: 5px;
    text-align: center;
    background-color: beige;
    border: 1px solid gray;
}

.tableDiv table, .tableDiv td {
    border: 1px solid gray;
    border-collapse: collapse;
}

.tableDiv table td {
    padding: 5px 10px;
}

To summarize the situation:

  1. Above we have the index.js file serving the formatted getDates.html file incorporating CSS styles into the browser for retrieving necessary data.
  2. Upon entering start and end dates and clicking confirm, a fetch get request is dispatched to the server.
  3. No errors are observed in the browser console upon button click confirmation.
  4. The server successfully receives the request and organizes the data for usage in the pug template file, which when logged in the console shows up as expected. This indicates that everything is functioning correctly until the point of 'console.log( fData )' in index.js and therein lies the issue.
  5. However, the pug file report.pug fails to render on the browser.
  6. Curiously, directly typing 'http://localhost:5000/2021-04-01/2021-04-10' into the address bar and hitting enter triggers proper rendering of the pug template !!!!!!!

I'm currently mystified by this behavior. My queries are two-fold:

  1. Is the fetch request appropriately configured to retrieve dynamic results based on date?
  2. Could there be an error on the server side impeding the template rendering process?

Your insights and guidance would be greatly appreciated.

Answer №1

Your understanding of the fetch API needs some clarification

When you use Fetch, it actually returns a promise, so you have to use the `then` method to get the result. If you need more guidance, there is excellent documentation on how to utilize fetch available at MDN

To achieve what you are trying to do, a simple solution would be assigning the desired URL like this

window.location.pathname = `/${data.sdate}/${data.edate}`

This code snippet will effectively redirect your user, which seems to be the desired outcome.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When feeding a valid JSON to Datatable, it unexpectedly displays "No data available in table" instead of populating

I have been attempting to initialize data tables and provide it an array of objects. However, I keep encountering an error message stating that there is No data available in table. Surprisingly, when I check the console output, it clearly shows that this i ...

Trouble with Google Maps API clicking on url links

I've added markers to a Google Map and I'm trying to open the specific country's PHP page when a marker is clicked, but for some reason it's not working. Below is an example of my code: <script> function initMap() { var ger ...

What exactly is this issue? TypeError: Unable to retrieve property '0' from undefined

Encountering an issue while attempting to implement user authentication using mongodb and express. The error triggers every time the submit button is clicked on the website. This presents the first problem, followed by a second issue where the page continu ...

The functionality of $watch in AngularJS is not meeting the desired outcomes

Within my controller, I am looking to receive notifications when the value of a certain variable changes. Specifically, I want a function to be triggered whenever this variable is updated. To achieve this, I am utilizing the $watch method in AngularJS. Her ...

Typing a Character Automatically Focuses on Input Field

I have a situation where I want to focus on an input field when the user presses the '/' key. The issue is that once the element is focused, it automatically adds the '/' key to the input field because of how the detection is set up. do ...

In vuex, dynamic modules share common data and do not have unique data

Currently, I am facing an issue with an asynchronous API call that returns an array of objects. After receiving this data, I map it to dynamically registered modules in my store. The process looks something like this: dispatch // prior to this dispatch, ...

What is the process for turning off caching in CORS-Anywhere?

Encountering an issue with CSRF token validation while making a POST request to an endpoint on a different server using cors-anywhere. The error occurs because the CSRF Token passed to the cors-server is cached, leading to validation failure. Referenced a ...

What are the benefits of having a dedicated REST backend API?

Background: I am a novice programmer who is self-taught in the hopes of creating a Single Page Application. I have started learning JavaScript, jQuery, PHP, and MySQL, and now feel quite comfortable with all of them. I began working with Ember, but now I a ...

"Selections provided in the Summernote drop-down list

We are currently utilizing the Summernote rich-text editor (within MVC core) and have a need to incorporate a drop-down menu with varied display text in the menu, alongside the actual placeholder text that will be inserted into the editor. While we have f ...

Guide on iterating through an array of objects a specified number of times to ensure it loops through all child arrays within the objects, if they exist

How can I iterate through an array of objects a certain number of times to access all the child arrays within each object and retrieve their IDs in order? let data = [{ "id": "1", "child": [ { "id": "12", "child": [ { ...

When combining node.js, express 3, and socket.io, an error may occur stating "Cannot set headers after they are sent."

As I venture into the world of node.js, I've encountered a perplexing error that has me stumped. The code in question is quite basic and geared towards beginners, so I'm puzzled as to why it's behaving differently on my production server co ...

Discovering a user's role in a WordPress site within an Angular application

I am currently in the process of integrating an Angular application into a WordPress theme. Certain Angular components need to verify if a user is logged in and has a specific role in order to display certain content. Since WordPress is built on PHP and An ...

Can JavaScript be used to retrieve the name of the function currently being executed in the code?

As an illustration: function example() { console.log(info); } will display example or function test() { function demo() { console.log(description) } } will demonstrate test/demo The specific structure is not crucial, as long as the ...

TypeB should utilize InterfaceA for best practice

I have the following TypeScript code snippet. interface InterfaceA { id: string; key: string; value: string | number; } type TypeB = null; const sample: TypeB = { id: '1' }; I am looking for simple and maintainable solutions where TypeB ...

Developing an Addon for Firefox using XUL and JavaScript

I am interested in creating a Firefox Addon that dynamically generates a button in the webpage's DOM when a specific page like www.google.com is loaded. This button, when clicked, will redirect to another page such as www.stackoverflow.com. It is imp ...

Steps for deploying a Next.js frontend and a separate Express backend:1. First,

I am in the process of developing an application that utilizes next.js for the frontend and a standalone backend server built on express. As I plan for production deployment, I am concerned about costs and the most efficient approach to take. Although I ha ...

Utilizing Object-Oriented Programming to organize and store data within a class object

After successfully running a class to fetch all data and store it in an object, I noticed that the object (AllOptions) is undefined. I have attempted to find a suitable solution but have been unsuccessful. router.get('/:category', (req, res) =& ...

Intelligent Scrolling with Bootstrap 4

Utilizing a basic tutorial from here to implement show/hide functionality for a standard BS4 navbar on scroll. Works flawlessly on desktop. However, facing an issue with the mobile view where the navbar behaves oddly when scrolling down and returning to t ...

I encountered difficulties with the textbox textchange feature when working in ASP.NET using C#

I have a TextBox in my popup page. I need to determine if the text entered in the TextBox is "Admin" by using TextBox.Text.Equals("Admin"); Here is how the TextBox is defined: <asp:TextBox ID="TextBox1" runat="server" Height="35px" ontextchange ...

What is the method for adjusting the width of GridHelper grid lines?

Currently, I am utilizing Three.js (v0.86.0) to render a grid: let grid = new THREE.GridHelper(1000, 20); scene.add(grid); Upon inspection, the lines generated by GridHelper appear to have a thickness of 1 pixel. I am interested in increasing the thickn ...