Pankesh Patel
Pankesh Patel

Reputation: 1302

polling node.js service periodically

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();
    });

Upvotes: 0

Views: 1070

Answers (1)

Meir
Meir

Reputation: 14375

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.

Upvotes: 1

Related Questions