0

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

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
Shalafister's
  • 761
  • 1
  • 7
  • 34

1 Answers1

0

The problem lies in that you call res.render() over and over again every 2 seconds in your route.get() handler - you can only have ONE final res.render() per request handler. You can't expect your website to automatically update itself every 2 seconds after a request is made, in the way you coded. You can either have the client send the request every N seconds (not efficient, mind you) or use something more efficient such as web socket to achieve that.

Rico Chen
  • 2,260
  • 16
  • 18
  • I 'm now using socket.io, but I could not update the view after the http request. When I use `io.connect..` and inside cron job. Whenever a user connects it sends multiple http requests. – Shalafister's Dec 26 '17 at 02:29
  • Without seeing how you use socket.io in your server/client I am not sure what the problem is. Also using io.connect inside your cron job smells problems already, I think. – Rico Chen Dec 26 '17 at 02:43