簡體   English   中英

定期輪詢node.js服務

[英]polling node.js service periodically

在我當前的項目中,我試圖訪問傳感器數據並將其繪制到Web瀏覽器中。 以下代碼(在node.js中)隨機生成溫度值,其他代碼則定期將其輪詢到服務並將其繪制到Web瀏覽器。 我的問題是,當我運行此代碼時..我的瀏覽器未打印任何內容,並且在控制台中收到以下消息。 您能告訴我這段代碼有什么問題嗎?

未聲明HTML文檔的字符編碼。 如果文檔包含來自US-ASCII范圍之外的字符,則在某些瀏覽器配置中,文檔將呈現亂碼。 頁面的字符編碼必須在文檔或傳輸協議中聲明。

跨域請求被阻止:同源策略禁止讀取位於http:// localhost:8686 / temperature的遠程資源。 (原因:CORS標頭“ Access-Control-Allow-Origin”缺失)。

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

以下是使用URL定期輪詢node.js代碼的客戶端代碼:“ http:// localhost:8686 / temperature ”。 我正在使用Google可視化庫隨機繪制溫度。

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

在評論中回答了我的問題之后(@tiblu也指出了這一點),嘗試從服務器提供html文件並通過訪問http:// localhost:8686 / index.html (或任何您稱呼的文件)來訪問它。

如果使用express,則可以使用express.static來完成。 如果您決定堅持使用http模塊,請查看如何提供靜態文件。 這是一個看起來很有用的例子

在本地加載html文件后,請dbl單擊資源管理器,然后將其打開為file://path/to/your/directory/index.html。該文件與localhost:8686的來源不同。 通常,在開發節點全棧應用程序(這也具有前端)時,這是一個好習慣,它可以通過本地服務器而非文件系統打開文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM