How to render static HTML with JSON data with no client-side javascript?

Viewed 1420

I have a json file with an array of data I would like to display on a website, currently, I just use Javascript and use fetch as:

fetch('file.json').then(response => {
   return response.json();
}).then(response => {
   //response = {list: [{item: 1}, {item: 2}, {item: 3}]}
   response.list.forEach(listItem => {
     document.body.innerHTML += `${listItem.item} `;
   });
});

However, I don't want to have the client make a call to fetch a file that contains the same data every time. I looked into SSR frameworks, but at the same time, I don't want the server to render the same .html file over and over.

What I'm looking for is a way to render a .html file with data from this .json and just host it as a static page, (Node.js preferred). Is there a node module or script that can render this page as a .html file with no requirements such as:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>title</title>
  </head>
  <body>
    1 2 3 4
  </body>
</html>
2 Answers

I may be wrong but, what I understood with your question is that you may want to render HTML as a response. So, if you want to render HTML as a response, I would write below code:

const http = require('http');
const fs = require('fs');

const onRequest = (request, response) => {
   response.writeHead(200, {
    'Content-Type': 'text/html',
   });

   fs.readFile('./index.html', null, (error, data) => {
     if (error) {
        response.writeHead(404);
        response.write('File Not Found.');
     } else {
        response.write(data);
     }

     response.end();
  });
};

http.createServer(onRequest).listen(8000);

The trick is to set Content-Type as text/html to render index.html as website page. You can modify above code to edit index.html content. Let me know if my answer is not helpful at all.

If you're vehement on not using client-side javascript, and instead just want to render it on the server side, perhaps you should look into something like EJS. It's typically "better practice" to render with client-side javascript/jquery, so it's easier to make dynamic, but...

With this it's pretty easy to do. There's examples on their site on how to use it, but once you've installed it on the server side, it's practically as easy as...

app.set('view engine', 'ejs');

// your server code

app.render('index.ejs', { "foo": "bar" );

Your index.ejs syntax would look something like

<p> <%= foo %> </p>

Which would render out to

<p> bar </p>
Related