Luiz Henrique
Luiz Henrique

Reputation: 103

Socket I.o doesn't automatically update

I am using the Socket ith and when I send a POST / EnviaTemperatura is not updating automatically on my site. what am I 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 is only updating when I the one Refresh the page. But I did not want to refresh the entire page, only that DIV, as have other elements on the screen that take a while to load.

What could it be?

Upvotes: 1

Views: 1269

Answers (1)

mk12ok
mk12ok

Reputation: 1313

Try this:

'use strict';
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const temperatureSender = new MyEmitter();

and then inside the app.post:

temperatureSender.emit( 'sendTemp', temperature);

and inside the io.on('connection',..):

temperatureSender.on('sendTemp', function(temperature) {
    socket.emit('RecebTemp', temperature);
});

Upvotes: 1

Related Questions