Updating data realtime in Node.js express website
You could:
- Get rid of socket.io.
- Make an end point for retrieving the temperature.
- Do some polling on the frontend.
Backend would look something like this:
var express = require('express');
var app = express();
var server = require('http').Server(app);
app.get('/weather', function (req, res) {
res.send(getTemperature())
});
Frontend would look something like this:
doctype html
html
head
link(rel='stylesheet', href='/css/index.css')
title Dashboard
body
.main-content
h1(id='weather') Weather is: // I WANT THIS TO BE UPDATED
script.
setInterval(function () {
fetch('/some/url', {
method: 'get'
}).then(function(response) {
// UPDATE WEATHER HERE
document.getElementById('weather').innerHTML = response
}).catch(function(err) {
// Error :(
});
}, 1000) // milliseconds
Code is totally untested, so please try not to copy and paste — adapt it instead. Also, if you're going to use the fetch API, you might want to use a polyfill, otherwise, just use plain ajax.
Shard
Updated on June 04, 2022Comments
-
Shard almost 2 years
I'm trying to achieve something what I think should be very simple to do, but all the tutorials and examples I find seem to be an overkill.
What I am doing: I'm fetching weather info periodically, and I want to update the text on the website everytime its fetched without user having to refresh the browser.
Almost every tutorial on realtime data updating recommends using socket.io and I have given it a try, but I can't get it to do what I want and I'm starting to think that there should be an easier way and that socket.io might not be the best way to go about this. Any suggestions? How do I get simple line of text update on website without user having to refresh the page?
My weather script:
var express = require('express'); var app = express(); var server = require('http').Server(app); var io = require('socket.io')(server); function refreshWeather() { var temperature = getTemperature(); io.sockets.emit('broadcast', { temperature : temperature }); }
My jade script:
doctype html html head link(rel='stylesheet', href='/css/index.css') title Dashboard body script(src='/socket.io/socket.io.js') script. var socket = io(); socket.on('broadcast', function (data) { // UPDATE WEATHER HERE }); .main-content h1 Weather is: // I WANT THIS TO BE UPDATED