0

In my current project, I am trying to access the sensor data and plot it to web browser. The following code (in node.js) that generate temperature value randomly and the other code polls the to the service periodically and plot it to web browser. My problem is that when I run this code.. my browser is plotting nothing and I am getting following message in console. could you please advise what is the wrong with this code?

The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8686/temperature. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

var http = require("http");
var port = 8686;

function randomInt (low, high) {
  return Math.floor(Math.random() * (high - low) + low);
}

http.createServer(function(req,res){
  console.log('New incoming client request for ' + req.url);
  res.writeHeader(200, {'Content-Type': 'application/json'}); 
  switch(req.url) {

    case '/temperature':
      // And return the corresponding JSON
      res.write('{"value" :' + randomInt(1, 40) + '}');
      break;        
  }
  res.end(); 
}).listen(8686);
console.log('Server listening on http://localhost:' + port); 

The following is the client code that poll the node.js code periodically using URL: 'http://localhost:8686/temperature'. I am using Google visualization library to plot the temperature randomly.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript"
            src="https://www.google.com/jsapi?autoload={
    'modules':[{
      'name':'visualization',
      'version':'1',
      'packages':['corechart']
    }]
  }">
</script>
</head>

<body>
<div id="chart" style="width: 900px; height: 500px"></div>
<script type="text/javascript">
    $(document).ready(function () {
        var maxDataPoints = 10;
        var chart = new google.visualization.LineChart($('#chart')[0]); 
        var data = google.visualization.arrayToDataTable([ 
            ['Time', 'Temperature'],
            [getTime(), 0]
        ]); 

        var options = { 
            title: 'Temperature',
            curveType: 'function',
            animation: {
                duration: 1000,
                easing: 'in'
            },
            legend: {position: 'bottom'}
        };
        function addDataPoint(dataPoint) { 
            if (data.getNumberOfRows() > maxDataPoints) {
                data.removeRow(0);
            }
            data.addRow([getTime(), dataPoint.value]);
            chart.draw(data, options); 
        }

        function getTime() {
            var d = new Date();
            return d.toLocaleTimeString();
        }

        function doPoll() { 
            $.getJSON('http://localhost:8686/temperature',
                    function (result) {
                        console.log(result);
                        addDataPoint(result); 
                        setTimeout(doPoll, 2000);
                    });
        }

        doPoll();
    });
user-517752
  • 1,188
  • 5
  • 21
  • 54
  • Google about "same origin policy" and CORS – slebetman Oct 03 '15 at 15:56
  • The FE code is fine, tested it by generating random number in FE, in the ``doPoll`` (http://codepen.io/anon/pen/ojZEQm). So it must be data access issue as @slebetman said. and you should be seeing "XMLHttpRequest cannot load .... No 'Access-Control-Allow-Origin' header is present on the requested resource...". Make sure you don't have any filters applied on the console that may hide the error. The best article on CORS is - https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS. So in short - it should work IF the FE (html) is also served from localhost:8686. – tiblu Oct 03 '15 at 16:11
  • 1
    In addition, please check also "network" tab for errors, not just the console. – tiblu Oct 03 '15 at 16:12
  • Thanks slebetman and tiblu for the response! I am bit new to web development. could you please advise -- how could I fix this issue? I am using Mozila firefox to test . – user-517752 Oct 03 '15 at 17:01
  • I have attached the error with question now for you reference. – user-517752 Oct 03 '15 at 17:20
  • @Bigood : I am not using express. I have just created app.js file and copy the above code and run it. – user-517752 Oct 03 '15 at 17:58
  • Where are you loading your html from? Do you open it as a local file? – Meir Oct 03 '15 at 19:28
  • Serve the HTML also from http://localhost:8686/ and it will work. It won't work if you open the HTML as a file from disk. – tiblu Oct 03 '15 at 22:25
  • @Meir : I am opening the HTML file just in browser as a local file. – user-517752 Oct 04 '15 at 02:53
  • @tiblu : thanks ! I did not get you. Should I copy the HTML file into the folder in which node.js file is ? – user-517752 Oct 04 '15 at 02:58
  • @tiblu : Since I have been using node.js, I have followed this guidline to run HTML file : https://github.com/skeelogy/ifc-ar-flood/wiki/Running-The-HTML-Files-Locally-In-Your-Web-Browser. Please feel free to correct me ! – user-517752 Oct 04 '15 at 03:50

1 Answers1

1

Following your reply to my question in the comments (@tiblu also pointed it out), try to serve your html file from the server and access it by accessing http://localhost:8686/index.html (or whatever you call it).

If you used express, this could be done using express.static. If you decide to stick with using the http module, check out how to serve static files. This is one example that looks useful.

Once you load your html file locally - dbl click in the explorer and have it open as file://path/to/your/directory/index.html - it is considered a different origin than localhost:8686. In general, it is a good practice when developing a node full stack app, meaning that has a front end as well, to open the files via your local server and not the file system.

Community
  • 1
  • 1
Meir
  • 14,081
  • 4
  • 39
  • 47
  • Thanks for the answer! Still I am in confusion. What does it mean of your statement "Try to serve your html file from the server and access it by accessing http://localhost:8686/index.html (or whatever you call it).". – user-517752 Oct 04 '15 at 07:03
  • I follow this procedure to serve my html file from the server, as mentioned on link (https://github.com/skeelogy/ifc-ar-flood/wiki/Running-The-HTML-Files-Locally-In-Your-Web-Browser). Is it correct? Feel free to correct me. – user-517752 Oct 04 '15 at 07:03
  • 1
    The procedure is okay but will probably generate the same problem. The issue is that a page from domain A (say localhost:8080) tries to access a server from domain B (localhost:8686). Just add a case to your server routing: case '/index.html': code to return your html file content. Hope this is clear enough, if not, don't hesitate to ask again – Meir Oct 04 '15 at 07:15
  • thanks again! I am bit new to node.js. My node.js project contains "routes" folder. It has two files : (1) index.js (2) user.js. Should I edit index.js file?/or other. I am attaching the content of index.js file. kindly revert back to me the content that should be added: exports.index = function(req, res){ res.render('index', { title: 'Express' }); }; – user-517752 Oct 04 '15 at 07:36
  • This looks fine. What does the address bar of your browser says when you open the index file? – Meir Oct 04 '15 at 07:37
  • Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8686/temperature. (Reason: CORS header 'Access-Control-Allow-Origin' missing). - Kindly see the content of index.html file (It has been mentioned in the question) – user-517752 Oct 04 '15 at 07:43
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/91284/discussion-between-pankesh-and-meir). – user-517752 Oct 04 '15 at 07:49