I'am trying to make a HTTP request every 2sec by using the node-cron
module.
I have apiCalls.js;
var http = require('https');
module.exports = {
getData: function(callback) {
var options = {
host: 'google.com',
path: '/index.html'
};
var req = http.get(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
var bodyChunks = [];
res.on('data', function(chunk) {
bodyChunks.push(chunk);
}).on('end', function() {
var body = Buffer.concat(bodyChunks);
console.log('BODY: ' + body);
callback(body);
})
});
req.on('error', function(e) {
console.log('ERROR: ' + e.message);
});
}
}
This works just fine. I would like to call this every 2 sec and later I would like to update the view file. Here I do not know if I need socket.io
or I can do it with react.
I'm calling this function in index.js;
var express = require('express');
var router = express.Router();
var cron = require('node-cron');
var apiCalls = require('../apiCalls')
router.get('/', function(req, res, next) {
var cronJob = cron.schedule('*/2 * * * * *', function(){
apiCalls.getData(function(data){
res.render('index', { title: 'example', data: data });
});
});
cronJob.start();
});
module.exports = router;
But I'am getting error, as it seems I have already set the headers. How can I do that?
_http_outgoing.js:503
throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'set');
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at validateHeader (_http_outgoing.js:503:11)
Thank you