A
A
Alexander2016-08-02 09:12:31
Node.js
Alexander, 2016-08-02 09:12:31

Node js: Error: Can't set headers after they are sent what happened?

error:
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:689:11)
the code is here:

exports.Load = function (req, res, next)  {
  
var bodyParser = require('body-parser');   
var crypto = require('crypto');
var Connection = require('tedious').Connection; 
var _ = require('underscore');

var Request = require('tedious').Request;  
var TYPES = require('tedious').TYPES; 

if (!req.params.data ){
res.setHeader('Access-Control-Allow-Origin');
    res.send('{"error":"invalid data"}'); 
    next();
}else{
        
var obj = JSON.parse(req.params.data);
var ini_uid = obj.uid;
var ini_key = obj.key;
     
var connection = new Connection(config); 
  connection.on('connect', function(err){
     if(err){
    console.log(err);
   next();    
    }else{
        var request = new Request("SELECT *  FROM ТУТ WHERE ВОТ", function(err, rowCount, rows){
         connection.close();
          next();  
        })
        request.on('row', function(columns) {

if(columns[11].value == ini_key){

///
var connection = new Connection(config); 
connection.on('connect', function(err) { 

request = new Request("SELECT * FROM ВОТ ЭТО WHERE ВОТ ТАКОЕ ORDER BY ЧТО-ТО DESC ", function(err, rowCount) { 
connection.close(); 
}); 
request.on('row', function(columns) { 
 res.setHeader('Access-Control-Allow-Origin');
 res.json({error: columns });
  return next();


}); 
connection.execSql(request); 
});

}else{
 res.json({error: "invalid data" });
res.setHeader('Access-Control-Allow-Origin');
  return next();
}

        })
     connection.execSql(request);
    }

  })

}
return;
};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-08-02
@maxfarseer

The error says that your express is trying to respond with a header (in the style of "Status 200" - everything is OK).
The problem is that you already had an answer, and he cannot answer again. Literally: Can't set headers after they've been sent.
The solution is to always use the return keyword when you "reply". In your example it's either res.json or next. The point is this.
Example from api:
If we remove return, then in case of an error, we will get into if (err) ..., we will answer as an error (400), and we will not exit the function routing, we will go below and we will answer as success (200) - and bam -c, get an error - can't set headers...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question