简体   繁体   中英

can't set headers after they are sent return res.json

exports.saveUserInterfaceConfig = function(req,res){
  var body = req.body;
  console.log('body:['+JSON.stringify(body)+']');
  var mysql = require('mysql');
  var UiConfigId = [];
  var connection = getDBConnection();
  if(body && connection){
    connection.beginTransaction(function(err){
      if (err) {
        /*var errorObj = {error:{code:0, text:'backend error'}};
         return res.json(200, errorObj);*/
        throw err;
      }
      var companyId = body.companyId;
      var moduleId = body.moduleId;
      var submoduleId = body.submoduleId;
      var formfieldsId = body.formfieldsId;
      for(var index3 in formfieldsId){
        var UIConfigInfo  = {Company_CompanyId: companyId, Modules_ModuleId: moduleId, SubModule_SubModuleId: submoduleId, SubmoduleFieldConfig_SubmoduleFieldConfigId: formfieldsId[index3]};
        var saveUIConfigQuery = 'INSERT INTO ui_config SET ?';
        connection.query(saveUIConfigQuery, UIConfigInfo, function(err, result) {
          if (err) {
            return connection.rollback(function() {
              throw err;
            });
          }
          UiConfigId.push(result.insertId);
          console.log('result:['+JSON.stringify(result)+']');
          connection.commit(function(err) {
            if (err) {
              return connection.rollback(function() {
                connection.end(function(err) {
                  // The connection is terminated now
                });
                throw err;
              });
            } else {
              connection.end(function(err) {
                // The connection is terminated now
              });
            }
            return res.json(200,{UiConfigId: UiConfigId});
            console.log('UiConfigId:['+JSON.stringify(UiConfigId)+']');
            console.log('success!');
//                          connection.release();
          });
        })

      }

    })
  }
}

I have the above in my Node API. I have to execute same query in loop more than once . but im facing an issue placing the return statement for which im getting the below error.

Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)

How do I fix it?

The reason you are getting that error is because you are calling res.json multiple times in a loop.

First of all, you should be using a callback mechanism to execute the query in a loop. For'ing over it can mess up by executing multiple queries before even the others are finished.

And coming to the response, it also should be done through a callback based on a condition. Condition can be to check whether you have finished all the queries successfully.

Here is a page with good info on exactly what you need: https://mostafa-samir.github.io/async-iterative-patterns-pt1/

you are calling res.json multiple times in a loop, that is the reason you are getting that error..

In Simple Words., This type of error will get when you pass statements or something after sending response.

for example:

res.send("something response");
console.log("jhgfjhgsdhgfsdf");
console.log("sdgsdfhdgfdhgsdf");
res.send("sopmething response");

it generates, what the error u got.!! Beccoz once the response have been sent, the following res.send Will not be executed..because, we can send response only once per a request.!! for this you need to use the callbacks.

Good Luck

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