How do I modify the page I'm serving in node.j

2019-07-28 17:36发布

问题:

Ok, so I have my server.js

var express     = require("express"),
    app         = express(),
    bodyParser  = require('body-parser');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(express.static(__dirname + '/'));

app.post('/message', function(req, res) {
  var jsonData = req.body;
  if (jsonData.hasOwnProperty('phone1')) {
      console.log("Phone 1 is connected to", jsonData.phone1.connection,
                  "and has a downlink speed of", jsonData.phone1.dl, "Mbps");
  } else 
  if (jsonData.hasOwnProperty('phone2')) {
      console.log("Phone 2 is connected to", jsonData.phone2.connection,
                  "and has a downlink speed of", jsonData.phone2.dl, "Mbps");
  }
});

var port = 1337;
app.listen(port);
console.log("Running at Port " + port);

and as you see I want to do stuff when the server gets something posted on /message. I can console.log stuff yes, but I want to change things on the web page this server is serving. The POST requests are coming from another server. This server only presents them.

How can I do that without having to update the page?

I'm also using AngularJS on the client side, so any way for the client side to pick up the JSON data would be nice.

I hope to present the data in my Highcharts gauges and charts but a simple text update on a page element (e.g. <p id="example">) will do just fine for an answer to this question.

I know I can get jquery to node but I still lack the window element to manipulate the presented data. NW.js might do exactly what I want, I haven't still tried it though, but I suspect there might be another solution to this problem.

回答1:

If you want to push new content to the client (opposite flow to the client requesting data from the server), WebSockets are an option (see http://socket.io/ for a common library).

Alternatively, you could setup long polling on the client side. This is using JavaScript to periodically 'poll' the server for information using setInterval or a similar approach.



回答2:

Since I only need to send data from the server to the client, I ended up with Server Sent Events (SSE) and my code looks like this on the server side:

var mypage;

app.get('/connect', function(req, res){
    res.writeHead(200, {
      'Connection': 'keep-alive',
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache'
    });
    mypage = res;
});

app.post('/message', function(req, res) {
    if (mypage !== undefined) {
        mypage.write('data: '+ JSON.stringify( req.body ) +'\n\n');
    }
});

and on the client side:

$(function () {
    var server = new EventSource('/connect'),
        point1 = $("#gauge1").highcharts().series[0].points[0],
        point2 = $("#gauge2").highcharts().series[0].points[0];
    server.onmessage = function(e) {
        var jsonData = JSON.parse(e.data);
        if (jsonData.hasOwnProperty('phone1')) {
            point1.update(parseInt(jsonData.phone1.dl));
            if (jsonData.phone1.connection === "3G") {
                /* extra functionality */
            } else {
                /* extra functionality */
            }
        } else 
        if (jsonData.hasOwnProperty('phone2')) {
            point2.update(parseInt(jsonData.phone2.dl));
            if (jsonData.phone2.connection === "3G") {
                /* extra functionality */
            } else {
                /* extra functionality */
            }
        }
    };
});

I got extra help from my other question regarding the data formatting of SSE

Node Webkit was not the answer to my problem, since it doesn't run on the browser.

I still have some problems with receiving many posts. I'm generating every 0.5s a post message but I keep receiving 5 messages then nothing for 2 minutes then again 5 messages. I don't know why that's happening, but it's not part of this problem so I'll post another question about that.