sruthi karan
sruthi karan

Reputation: 21

send multiple responses to client via nodejs

i am using nodejs and i want to send back multiple responses to client.And my code is below

//addwork

var agenda = require('../../schedules/job-schedule.js')(config.db);

    exports.addwork = function(req, res) {

        var work = new Work(req.body);
        work.user = req.user._id;
        var user=req.user;
     work.save(function(err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {

                console.log('created work....'+work);
                console.log('dateeeeeeeeeeeee'+work.created);
                console.log('calling agenda job now, user is: '+ JSON.stringify(req.user));
                    console.log('supervisor-------------------------'+JSON.stringify(user.supervisor));
                agenda.now('Work_To_Supervisior_Notify', {supervisor:user.supervisor,title:work.title,details:work.details});

    res.jsonp(work);
                    res.send({message:'An email has been sent to ' + user.supervisor + ' with further instructions.'});

            }
        });
    };`

//job-schedule.js

var Agenda = require("agenda");
    var emailJob = require('./jobs/email-job.js');
module.exports = function(agendaDb) {

    var agenda = new Agenda({db: { address: agendaDb}});


    emailJob.sendWorkToSupervisiorEmail(agenda);

    agenda.start();
    return agenda;
}

//email-job.js

   exports.sendWorkToSupervisiorEmail = function(agenda){
        agenda.define('Work_To_Supervisior_Notify',{priority: 'high', concurrency: 10}, function(job, done){
            console.log('Send works to supervisior ' + JSON.stringify(job.attrs.data.supervisor)+' ,title '+job.attrs.data.title+' ,details '+job.attrs.data.details);
            var smtpTransport = nodemailer.createTransport(config.mailer.options);
                var mailOptions = {
                    to: job.attrs.data.supervisor,
                    from: config.mailer.from,
                    subject: 'work done by user',
                    html: '<b>work title : '+job.attrs.data.title+' <br/>work details : '+job.attrs.data.details+'</b>'
                };

                    smtpTransport.sendMail(mailOptions, function(err) {
                    if (!err) {
                        console.log('An email has been sent to ' + job.attrs.data.supervisor + ' with further instructions.');
                    res.send({message:'An email has been sent to ' + user.supervisor + ' with further instructions.'}); 

                    }
                });

            done();
        })

    }

Here i want response either from agenda or from res.send() message in addwork function If i use res.send in addwork function it shows ERROR as "can't set headers after they sent".And if i use res.send message in sendWorkToSupervisiorEmail() it show ERROR as "there is no method send".I am new to nodejs please help me with solution

Upvotes: 1

Views: 3883

Answers (1)

clay
clay

Reputation: 6017

A http request only gets a single http response. Using http, you only get one response. Some options for you:

1) Wait for everything to finish before replying. Make sure each part creates a result, success or failure, and send the multiple responses at once. You would need some control flow library such as async or Promises to make sure everything responded at the same time. A good choice if all parts will happen "quickly", not good if your user is waiting "too long" for a response. (Those terms were in quotes, because they are application dependent).

2) Create some scheme where the first response tells how many other responses to wait for. Then you'd have a different HTTP request asking for the first additional message, and when that returns to your client, ask for the second additional message, and so on. This is a lot of coordination though, as you'd have to cache responses, or even try again if they were not done yet. Using a memory cache like redis (or similar) could fulfill the need to holding responses until ready, with a non-existent meaning 'not ready'

3) Use an eventing protocol, such as WebSockets, that can push messages from the server. This is a good choice, especially if you don't know how long some events would occur after the trigger. (You would not want to stall a HTTP request for tens of seconds waiting for 3 parts to complete - user will get bored, or quit, or re-submit.). Definitely check out the Primus library for this option. It can even serve the client-side script, which makes integration quick and easy.

Upvotes: 5

Related Questions