Socket I.o does not update automatically

Asked

Viewed 235 times

1

Hello, I am using Socket i.o and when I submit a POST /Enviatemperatura, it is not automatically updating on my website. What I’m doing wrong?

Node.js

app.post('/EnviaTemperatura', function(req, res){
    temperatura = req.body.temp;
    console.log(temperatura);
    res.send('Temperatura: ' + temperatura);
});

io.on("connection", function(socket) {
    socket.emit('RecebTemp', temperatura);
});

HTML

<div class="col-xs-9 text-right">
    <div class="huge"><span id="EnviaTemp">0</span> ºC</div>
    <div>Temperatura no Interior da casa</div>
</div>

<script>
    var socket = io();
        socket.on('RecebTemp', function (temperatura) { 
            document.getElementById("EnviaTemp").innerHTML = temperatura;
        });
</script>

In my case, it’s only updating when I give a refresh on the page. But I didn’t want to refresh the whole page, only in this DIV, since I have other elements on the screen that take a while to load.

What could be?

  • 1

    As your code currently stands, Emit is not running at the moment a POST request is made. Emit has to be within the app.post function. Of course, for that, you’ll need to adapt your code.

  • I will leave an answer to supplement this comment.

1 answer

1


In your Node.js code, switch to:

app.post('/EnviaTemperatura', function(req, res){
    temperatura = req.body.temp;
    io.sockets.emit("RecebTemp", temperatura);
    console.log(temperatura);
    res.send('Temperatura: ' + temperatura);
});

And remove this entire section:

io.on("connection", function(socket) {
    socket.emit('RecebTemp', temperatura);
});
  • 1

    exactly what I needed! Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.