0

i am new to JavaScript and Node JS. i have the following code:

app.post('/sendSensorsUserIds', function (req, res) {
  var myBody= req.body;
  var sensors= myBody.Sensors;
  var ids= myBody.ids;
  DButils.getSensorsUserIds(connection, ids , sensors , function(ids){
    return res.sendStatus(ids);
  });  
  res.end();
});

I always get the following error:

C:\Users\Daniel\Server\node_modules\mysql\lib\protocol\Parser.js:82
        throw err;
        ^

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

some one has any idea what is the problem?

Dan The Man
  • 1,835
  • 6
  • 30
  • 50

2 Answers2

0

res.end() is getting called before the callback in DButils.getSensorsUserIds. I suggest ,

app.post('/sendSensorsUserIds', function (req, res) {
  var myBody= req.body;
  var sensors= myBody.Sensors;
  var ids= myBody.ids;
  DButils.getSensorsUserIds(connection, ids , sensors , function(ids){
    return res.status(ids).end();
  });  

});
zahreelay
  • 1,742
  • 12
  • 18
-1

It is because you are sending the status after res.send() is executed. Try removing res.send();

app.post('/sendSensorsUserIds', function (req, res) {
  var myBody= req.body;
  var sensors= myBody.Sensors;
  var ids= myBody.ids;
  DButils.getSensorsUserIds(connection, ids , sensors , function(ids){
    return res.sendStatus(ids);
      });  

});
Keyur Sakaria
  • 680
  • 1
  • 5
  • 12