I would like to know how to pass the "myBlogs" variable that I have in my Node.js file ("server.js") to a frontend JavaScript file ("blogs.js"). Once I have access to it in the JS file, I would then map through the array that is stored in that variable and output a template for each blog in an HTML file ("blogs.html").
Later, the idea is to get the blogs data from a database (MongoDB) instead of having them hard coded. I have seen how to do this with Express and a templating engine (EJS), but as practice for a beginner, I would like to understand the basics of if and how it can be done without these tools.
My file structure:
blogs.css
blogs.html
blogs.js
server.js
server.js:
const http = require("http");
const fs = require("fs");
const myBlogs = [
{
title: "My first blog",
author: "John",
},
{
title: "My second blog",
author: "Mike",
},
];
const server = http.createServer((req, res) => {
console.log("request made");
// set header content type
let path = "";
switch (req.url) {
case "/blogs.css":
path += "blogs.css";
res.setHeader("Content-Type", "text/css");
break;
case "/blogs.js":
path += "blogs.js";
res.setHeader("Content-Type", "text/javascript");
break;
default:
path += "blogs.html";
res.setHeader("Content-Type", "text/html");
}
// send file
fs.readFile(path, (err, data) => {
if (err) {
console.log(err);
res.end();
} else {
res.write(data);
res.end();
}
});
});
server.listen(3000, "localhost", () => {
console.log("listening for requests on port 3000");
});
blogs.js:
const container = document.querySelector("div")
const html = myBlogs.map(blog => (
`<h2>${blog.title}</h2>
<p>${blog.author}</p>`
))
container.innerHTML = html;
blogs.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>Document</title>
<link rel="stylesheet" href="blogs.css" />
</head>
<body>
<div></div>
<script src="blogs.js"></script>
</body>
</html>
blogs.css:
p {
color: red;
}
P.S.: If such an approach is completely wrong, could you please explain the correct way this would be done without the use of Express and a templating engine?