0

i'm beginner at nodejs, i got a problem when request multiple url in a loop then i render it.

Error: Can't set headers after they are sent.

at validateHeader (_http_outgoing.js:491:11)

at ServerResponse.setHeader (_http_outgoing.js:498:)


router.get('/', function(req, res, next) {
  setInterval(function(){

             request(url1,function (error,response,body) {
                 var data1 = JSON.parse(body);

                 request(url2+data1.access_token,function (error,response,body) {
                 var data_info = JSON.parse(body);

                                   //error when it render
                               res.render('index', {data_info : data_info});
                            })
                        })
          },5000);
});
AbhinavD
  • 6,892
  • 5
  • 30
  • 40

2 Answers2

1

That's not exactly a loop, I understand you mean that you call the same function repeteadly with setInterval().

Once you've sent your first response with res.render(), which finishes the response process for that request, subsequent attempts to use that res object fail.

If you want to send data to the client in 5 seconds interval you should probably either look into websockets or pass the setInterval() calls to the client so it polls your server each 5 seconds, in which case your server code could be changed to:

router.get('/', (req, res) => {
  request(url1, (error, response, body) => {
    const data1 = JSON.parse(body);
    request(`${url2}${data1.access_token}`, (error, response, body) => {
      const data_info = JSON.parse(body);
      res.render('index', { data_info });
    });
  });
});
Miguel Calderón
  • 3,001
  • 1
  • 16
  • 18
0

You can make use of Async Module

const async = require('async');
router.get('/', function (req, res, next) {
   async.waterfall([
       function(callback) {
           request(url1, function (error,response,body) {
               if(err) {
                   callback(err)
               }else {
                    var data1 = JSON.parse(body);
                    callback(data1)
               }

           }) 
       },
       function(data1, callback) {
           request(url2+data1.access_token, function(error,response,body) {
                if(err) {
                   callback(err)
               }else {
                   var data_info = JSON.parse(body);
                    callback(null, data_info)
               }
           }) 
       }
   ], function(err, result) {
       if(err) {
           res.json({success: false, error: err, message: "Something went wrong.!"})
       }else {
            res.render('index', {
                data_info : result
            });
       }
   })
}) 
Anil Kumar
  • 187
  • 1
  • 9