2016-10-21 27 views
1
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(); 
      }); 
     }) 

     } 

    }) 
    } 
} 

我在上面的Node API中有上述信息。我不得不在循环中多次执行相同的查询。但即时通讯面临的问题放在返回声明,即时获取以下错误。发送后无法设置标题返回res.json

错误:发送后无法设置标题。 at ServerResponse.OutgoingMessage.setHeader(_http_outgoing.js:335:11)

如何解决?

回答

0

你是在一个循环中多次调用res.json,那就是你所得到的是错误的原因..

在Simple Words中,当你在发送响应之后通过语句或其他东西时,这种类型的错误会得到。

例如:

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

它会产生什么错误你长了!! Beccoz一旦发送了响应,下面的res.send将不会执行。因为我们每个请求只能发送一次响应。 为此,您需要使用回调。

好运

+0

感谢您的解释。我如何解决它? –

+0

使用回调为..建议它,当然你会得到一个想法.. https://mostafa-samir.github.io/async-iterative-patterns-pt1/ – Trojan

0

您得到该错误的原因是因为您在循环中多次调用res.json。

首先,您应该使用回调机制在循环中执行查询。在完成之前,通过执行多个查询可能导致混乱。

而即将到来的回应,它也应该通过基于条件的回调来完成。条件可以检查是否已成功完成所有查询。

这里是上好的准确的信息,你需要什么样的页面: https://mostafa-samir.github.io/async-iterative-patterns-pt1/