0

I am using Express Router as shown below

router.post('/do', function(req, res, next) {
   // some sample code
   var questions = new Questions();
   questions.display(req, res); 
});

The display function takes care of calling res.send.

In above snippet I am creating instance of Questions and passing req, res objects to it.

Now from my sample.js file I am firing almost 5 ajax requests to this same route and only one request is succeeding and after that I am getting error

Can't set headers after they are sent.

So I am not sure why I am getting this error!.

Can anybody help ?

UPDATE

Code in display function

Questions.prototype.display = function(req, res) {

  // Check if type of question exists
  if (req.body.questionType) {
    res.send({message: 'No Type found in request body!'});
  } else {
    // logic for getting questions from DB based on question type
    return res.send(questions);
  }
}
Pratik
  • 1,531
  • 3
  • 25
  • 57
  • Your function takes request while you pass req to your question. Assuming the error you print is from your express server it would be useful to see additional code from your question and question.display(). I'm running a server using express router in the same manner, and I run 10 requests to the same endpoint when building certain pages, and it works just fine, so that shouldn't be a problem. – Robin Mar 08 '16 at 09:51
  • @Robin: updated with code. – Pratik Mar 08 '16 at 10:11
  • I am not sure you still pass req, res into Questions ? var questions = new Questions(); questions.display(req, res); – Risto Novik Mar 08 '16 at 10:22
  • @RistoNovik: updated questions. I am passing `req` and `res` into display method. – Pratik Mar 08 '16 at 10:31
  • 1
    Well there is some code missing, there is some way you send already the response. Also remove the next from post handler function are you using some other middlewares also ? – Risto Novik Mar 08 '16 at 10:37
  • Before you run express server could you add env variable for debugging and post the results back here ```DEBUG=express:* node server.js``` – Risto Novik Mar 08 '16 at 12:24

1 Answers1

0

change request to req:

router.post('/do', function(req, res, next) {
// some sample code
var questions = new Questions(req, res);
questions.display(); 

});

see this

Community
  • 1
  • 1
sirk
  • 1
  • My Bad I was trying different approach. at that time it remained `request` but now updated again. – Pratik Mar 08 '16 at 10:18
  • add return before res.send({message: 'No Type found in request body!'}) if (req.body.questionType) { return res.send({message: 'No Type found in request body!'}); } else { // logic for getting questions from DB based on question type return res.send(questions); } – sirk Mar 08 '16 at 11:25