so guys I finally found an answer to my question, I hope you it will help you too. Follow these steps one by one to create a no refresh website using jquery, express and handlebars. Just a tutorial for something that is combination of multiple things.
1. Create a folder name mywebsite
2. run npm init and install the following dependencies
"express-handlebars": "^5.3.4",
"handlebars": "^4.7.7",
"hbs": "^4.1.2"
3. Now create a main.js file with the following code
const express = require('express')
const app = express();
const static_path = __dirname + "/static"
const hbs = require("hbs");
app.set('view engine', 'hbs');
app.set("views", __dirname + "/pages");
app.use(express.static(static_path));
var exhb = require('express-handlebars').create();
app.get("/", (req, res) => {
res.render('index', { title: "Home Test", pagename: "This is my Home page" });
});
app.get('/getabout', (req, res) => {
exhb.render("pages/about.hbs", { title: "About US page", body: "Body" }).then((html) => {
res.send({ data: html });
}).catch((err) => {
console.log(err);
})
});
app.listen(8080, 'localhost', () => {
console.log("listening at http://localhost:8080")
})
4. Now create a static folder with a file index.js and write the following code
async function callAbout() {
let data = await fetch('http://localhost:8080/getabout');
let response = await data.json();
console.log(response);
$("html").html(response['data']);
window.history.pushState(
'about us',
'About us',
'/aboutus');
}
5. Now create a pages folder with two files index.hbs and about.hbs index.hbs will contain the following code
<!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>{{title}}</title>
</head>
<body>
<h1>{{pagename}}</h1>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Sint assumenda aliquam dolor consectetur recusandae possimus illo praesentium atque nihil exercitationem!
<button onclick="callAbout()">About us</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
about.hbs will contain the following code
<!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>{{title}}</title>
</head>
<body>
<h1>This is my about us page created using NODE</h1>
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Explicabo accusamus autem accusantium suscipit, minima blanditiis ducimus quisquam fugiat, eligendi repellendus provident quasi dolores nesciunt laboriosam commodi illum repellat error eos.
{{body}}
</body>
</html>
6. Now run node.js and click the About Us button and see the magic
Hope this tutorial might help anyone trying to accomplish new things