简体   繁体   中英

Can't set headers after they are sent error. Node JS

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?

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();
  });  

});

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);
      });  

});

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