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>