简体   繁体   中英

multiple res.send/json - can't set headers after they are sent

I wanna know if it's possible do multiple res.send/json in same method. I have a big problem with that because I wanna develop a function into a Web-Worker to call a put request each minute but in 2nd request I get "can't set headers after they are sent.". I know that it's not possible do it but I wanna know if exist some way to run.

exports.update = function (req, res) {
      var feed = req.feed;
      feed.title = req.body.title;
      feed.apifeed = req.body.apifeed;
      feed.apikey = req.body.apikey;
      feed.active = req.body.active;

      if(feed.apifeed && feed.apikey && feed.active){

        var t = Threads.create();
        t.eval(setInterval(
          function(){

            async.parallel([
              function(callback, data){
                  var url = 'https://api.xively.com/v2/feeds/' + feed.apifeed + '.json?key=' + feed.apikey;
                  sensordata.getSensorData(url, function(data){
                    callback(null, data);
                  });
              }
            ], function(err, data){

                  feed.content[0].value = data[0][0].value;
                  feed.content[0].date = new Date();

                  feed.save(function (err) {
                      if (err) {
                        return res.status(400).send({
                          message: errorHandler.getErrorMessage(err)
                        });
                      } else {
                          res.json(feed);
                      }
                  });
            });

          }, 5000)
        );
      }
    };

Thanks for supporting and I wait your responses. Greetings!

You cannot respond to a request more than once, that wouldn't make sense.

If you need to stream data, then you will need to use long polling, WebSockets, Server-sent Events, etc.

Also, assuming Threads.create() does what I think it may be doing, spawning an OS thread just to do what you're currently doing is a waste of resources. Nothing in that block of code is CPU-bound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM