0

I have a file (in json format) somefile.json on my server which is regularly updated at selected time intervals.

I've a nodeJS app which reads the file on a request event listening at port 8080 and sends it out as response

How do I get javascript in a html to request for the json data and log it in console? (tried but failed, see below)

(Reason for the console.log is to let me know that it has been successfully loaded.)

My nodeJS app

var http = require('http'), 
    fs   = require('fs'),
    filename = "somefile.json"; 

var server = http.createServer();
server.on('request', function(request, response) { 
    response.writeHead(200, {'Content-Type': 'application/json'})
    fs.readFile(filename, "utf8", function (err, data) {
                if (err) throw err;
                response.write(JSON.stringify(data));
                response.end();
                });
    });

    server.listen(8080);

somefile.json

{
    "message": {
        "success":"Information inserted successfully.",        "update":"Information updated successfully.",
        "delete":"Information deleted successfully.",
    },
    "Jennifer": {
        "status":"Active"
    },    "James": {
        "status":"Active",
        "age":56,        "count":10,
        "progress":0.0029857,
        "bad":0
    }
}

using cURL on my local machine (OSX) gave me the following:

$ curl -i -H "Accept: application/json" http://127.0.0.1:8080
HTTP/1.1 200 OK
Content-Type: application/json
Date: Fri, 19 Sep 2014 03:39:41 GMT
Connection: keep-aliveTransfer-Encoding: chunked

"{\n    \"message\": {\n        \"success\":\"Information inserted successfully.\",\n        \"update\":\"Information updated successfully.\",\n        \"delete\":\"Information deleted successfully.\",\n    },\n    \"Jennifer\": {\n        \"status\":\"Active\"\n    },\n    \"James\": {\n        \"status\":\"Active\",\n        \"age\":56,\n        \"count\":10,\n        \"progress\":0.0029857,\n        \"bad\":0\n    }\n}\n"

my html (not working)

<html>                                                                                                                                                                                                                                                                          
<head></head>                                                                                                                                                                                                                                                                   
<body>                                                                                                                                                                                                                                                                          
<script src="jquery-2.1.1.min.js"></script>                                                                                                                                                                                                                                     
<script>                                                                                                                                                                                                                                                                        
$(function() {                                                                                                                                                                                                                                                                  
    $.ajax({                                                                                                                                                                                                                                                                
        url: 'http://127.0.0.1:8080',                                                                                                                                                                                                                                       
            contentType:"jsonp",                                                                                                                                                                                                                                            
            dataType: 'jsonp',                                                                                                                                                                                                                                              
            cache: false,                                                                                                                                                                                                                                                   
            success: function() { console.log('Success!'); },                                                                                                                                                                                                               
            error: function() { console.log('Uh Oh!'); }     
            });                                                                                                                                                                                                                                                                 
});                                                                                                                                                                                                                                                                             
    </script>                                                                                                                                                                                                                                                                   
</body>                                                                                                                                                                                                                                                                         
</html>       
altimit
  • 421
  • 5
  • 11
  • remove JSON.stringify – rnrneverdies Sep 19 '14 at 04:19
  • hey @rnrneverdies the console now gives "unexpected token" instead of logging out the json object – altimit Sep 19 '14 at 05:13
  • use dataType: jsonp for cross-domain request, that means request to different domain and dataType: json for same domain-same origin request. i suggest to use, dataType: 'json' – rnrneverdies Sep 19 '14 at 05:19
  • NOTE: I've added a error console.log (see the html) Also changing `dataType` to `json` However, this gives: `XMLHttpRequest cannot load http://127.0.0.1:8080/?_=1411105015186. No 'Access-Control-Allow-Origin'header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.` I tried adding the following to my header Access-Control-Allow-Origin':'*' in `response.writeHead` but it still logs the error message `Uh Oh!` – altimit Sep 19 '14 at 05:38
  • yes due the html was not downloaded from 127.0.0.1:8080, so its considerated cross-domain request. then if you provide the HTML from the same server that json, will work. but if you cant do this. go back to JSONP and read the answer given by ajiksharma. – rnrneverdies Sep 19 '14 at 05:41

2 Answers2

2

You can make AJAX calls to a backend API, it needs to return JSONP format and not just JSON, otherwise you get and error. This is due to same origin policy:
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy.

This discussion may be helpful to understand JSONP:

Can anyone explain what JSONP is, in layman terms?

However, one alternative is disable the security of Google Chrome browser, then it will work. But this is not a solution. You need to use JSONP format.

Community
  • 1
  • 1
ajitksharma
  • 4,523
  • 2
  • 21
  • 40
1

As you are using one source for html , and another source for json. This is considered a cross-domain request.

1 - Enclose your JSON object like this callbackname({data: value}).

var http = require('http'), 
    fs   = require('fs'),
    filename = "somefile.json"; 

var server = http.createServer();
server.on('request', function(request, response) { 
    response.writeHead(200, {'Content-Type': 'application/json'})
    fs.readFile(filename, "utf8", function (err, data) {
                if (err) throw err;
                response.write("callbackname(");
                response.write(data);
                response.write(")");
                response.end();
                });
    });

    server.listen(8080);

2 - Add jsonpCallback: "callbackname" to your ajax request.

<html>                                                                                                                                                                                                                                                                          
<head></head>                                                                                                                                                                                                                                                                   
<body>                                                                                                                                                                                                                                                                          
<script src="jquery-2.1.1.min.js"></script>                                                                                                                                                                                                                                     
<script>                                                                                                                                                                                                                                                                        
$(function() {                            

    $.ajax({                                                                                                                                                                                                                                                                
        url: 'http://127.0.0.1:8080',    
            jsonpCallback: "callbackname",
            contentType: "application/json",                                                                                                                                                                                                                                   
            dataType: 'jsonp',                                                                                                                                                                                                                                              
            cache: false,                                                                                                                                                                                                                                                   
            success: function(json){                                                                                                                                                                                                                                        
            console.log(json);                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                                               
            });                                                                                                                                                                                                                                                                 
});                                                                                                                                                                                                                                                                             
    </script>                                                                                                                                                                                                                                                                   
</body>                                                                                                                                                                                                                                                                         
</html>    
rnrneverdies
  • 15,243
  • 9
  • 65
  • 95
  • Got it! so the strings you attached at the front and end of the json string "callbackname(" and ")" gives you something similar to the foo({id:value}); in the link given by ajitksharma's http://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms – altimit Sep 19 '14 at 05:56