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:
- Express and Pug on the backend
- 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:
- Above we have the index.js file serving the formatted getDates.html file incorporating CSS styles into the browser for retrieving necessary data.
- Upon entering start and end dates and clicking confirm, a fetch get request is dispatched to the server.
- No errors are observed in the browser console upon button click confirmation.
- 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.
- However, the pug file report.pug fails to render on the browser.
- 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:
- Is the fetch request appropriately configured to retrieve dynamic results based on date?
- Could there be an error on the server side impeding the template rendering process?
Your insights and guidance would be greatly appreciated.