0

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?

2
  • Your handleRequest function response with index.html to every request. So when you request the json file your server response with index.html. Have you checked the output of console.log(data); in the getJSON function? It's most likely the content of index.html. Commented Nov 3, 2019 at 14:31
  • The $.getJSON() callback won't fire since the response is html not json. You need a more advanced handleRequest that also considers where request is made to nd responds accordingly Commented Nov 3, 2019 at 15:08

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Did it for me! Thanks !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.