节点服务器实时回显POST / URL参数

时间:2015-08-21 08:04:56

标签: ajax node.js arduino

我正在开发一个项目,我将通过Arduino将温度数据发送到Node服务器。 Arduino通过URL参数将数据发送到服务器:

http://localhost:3000/submit?temprature=25

然后我使用以下Node server.js

获取发布的数据
var express = require('express');
url = require('url');
var app = express();
app.get('/submit', function(req, res){
  var data = url.parse(req.url,true).query;
  console.log(data);
});
app.listen(3000, function(){
  console.log('listening on *:3000');
});

我能够用console.log()显示所需的数据,但我想要的是,只要Arduino通过URL参数发送数据,数据就会自动在服务器上回显/打印:{{1像实时一样。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

每次arduino设备更新温度时,您都可以使用socket.io发出事件:

var http = require('http');
var url = require('url');
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);  //pass a http.Server instance
server.listen(3000);  

app.get('/submit', function(req, res){
  var data = url.parse(req.url,true).query;
  io.emit('temperature', data);
  res.send('Temperature Updated to: ' + data.temperature);
});

app.get('/index', function(req, res){
    res.sendFile(__dirname + '/public/index.html');
});

然后在客户端,您可以侦听事件并更新信息。这是public/index.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Socket.IO Temperature Example</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
</head>
<body>

    <h1 id="temperature"></h1>

    <script>
      var socket = io('http://localhost:3000');
      socket.on('temperature', function (data) {
        console.log(data);
        $('h1#temperature').html(data.temperature);
      });
    </script>

</body>
</html>