Tom Truyen
Tom Truyen

Reputation: 363

Reading JSON file to HTML using jQuery

So I have a nodejs program that writes data into a JSON FILE. Now I have another node.js file which simply starts up a localhost server on: http://localhost:8000/ (which works) in that file I use fs.readFile to read my index.html file. Until this point everything works fine. Now when I go to my HTML file and I import jquery and open some script tags and try to get my json file (ITEM_FILE_LIST.json) using jQuery's getJSON it is not doing anything.

The JSON file looks like this:

[{"fileName":"File1.json"},{"fileName":"File2.json}]

This is my current HTML file & my Node.js file which creates the local server

All I need to be able to do is READ the JSON file into HTML, I don't need to write/append anything

<!DOCTYPE html>
<html>
    <head>
        <meta charset='utf-8'>
        <title></title>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" type="text/javascript"></script>
        <style type="text/css">

        </style>
    </head>
    <body>
        <div id="itemContainer">

        </div>
    </body>

    <script type="text/javascript">
        $.getJSON('ITEM_FILE_LIST.json', function(data) {
            console.log(data);
            var output = '<ul>';
            $.each(data, function(key,val) {
               output += '<li>' + val.fileName + '</li>'; 
            });
            output += '</ul>';
            $("#itemContainer").html(output);
        });
    </script>
</html>

============================================================================== //NODE JS FILE TO HOST LOCAL SERVER

var http = require('http');
var fs = require('fs');
var open = require('open');
var colors = require('colors/safe');

var messageShown = false;

var handleRequest = (request, response) => {
    response.writeHead(200, {
        'Content-Type': 'text/html'
    });
    fs.readFile('index.html', null, function (error, data) {
        if (error) {
            response.writeHead(404);
            respone.write('Whoops! File not found!');
        } else {
            response.write(data);
        }
        response.end();
    });

    if (!messageShown) {
        console.log(colors.green(time() + 'Don\'t close this prompt as long as you want to see the items!'));
        messageShown = true;
    }
};

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

(async () => {
     await open('http://localhost:8000/');
})();

function time() {
    var currentTime = '[' + new Date().getHours() + ":" + ((new Date().getMinutes()<10?'0':'') + new Date().getMinutes()) + ":" + ((new Date().getSeconds()<10?'0':'') + new Date().getSeconds()) + '] - ';
    return currentTime;
}

Thanks in advance

EDIT: I just checked and it does seem like instead of grabbing my JSON file the Ajax keeps getting the index.html data... Does anyone know a fix for this?

Upvotes: 0

Views: 536

Answers (1)

Ashish Tewari
Ashish Tewari

Reputation: 133

On a basic level, you may add conditions to the handleRequest function.

if (request.url === "/") {
response.writeHead(200, {
  "Content-Type": "text/html"
});
fs.readFile("index.html", null, function(error, data) {
  if (error) {
    response.writeHead(404);
    respone.write("Whoops! File not found!");
  } else {
    response.write(data);
  }
  response.end();
});
} else if (request.url === "/getjson") {
  response.writeHead(200, {
  "Content-Type": "application/json"
  });
  fs.readFile("ITEM_FILE_LIST.json", null, function(error, data) {
   if (error) {
     response.writeHead(404);
     respone.write("Whoops! File not found!");
   } else {
     response.write(data);
   }
   response.end();
  });
 }

Here, I have also added a new endpoint "/getjson", that needs to be added on the index.html as well, when getting the json.

$.getJSON('/getjson', function(data) {
        console.log(data);
        var output = '<ul>';
        $.each(data, function(key,val) {
           output += '<li>' + val.fileName + '</li>'; 
        });
        output += '</ul>';
        $("#itemContainer").html(output);
    });

Also, there was missing double quotes in your json, at end of File2.json

[{"fileName":"File1.json"},{"fileName":"File2.json"}]

Please check

Upvotes: 1

Related Questions