I'm working on a Node.js app (allowed in Heroku) which makes a response.write() and writes a JSON text. With hurl.it tool I can test these http requests and I can't understand why in the same http request, sometimes appear the first header or sometimes the other.
I only want the first one. How could I always have the first one and never the second?
HEADERS
Connection: Close
Content-Length: 877
Content-Type: application/json
Date: Wed, 26 Mar 2014 00:25:06 GMT
Or sometimes,
HEADERS
Connection: Close
Content-Type: application/json
Date: Wed, 26 Mar 2014 00:27:22 GMT
Transfer-Encoding: chunked
As you can see, I have no idea about what could it be, so I don't know which information could be useful to share. So if you've got any ideas, please share!
JSON is comes from a SQL query using mysql npm. Something like:
var mysql = require('mysql');
var db_config = {...};
var connection;
function handleDisconnect() {
console.log('1. connecting to db:');
connection = mysql.createConnection(db_config); // Recreate the connection, since
// the old one cannot be reused.
connection.connect(function(err) { // The server is either down
if (err) { // or restarting (takes a while sometimes).
console.log('2. error when connecting to db:', err);
setTimeout(handleDisconnect, 1000); // We introduce a delay before attempting to reconnect,
} // to avoid a hot loop, and to allow our node script to
}); // process asynchronous requests in the meantime.
// If you're also serving http, display a 503 error.
connection.on('error', function(err) {
console.log('3. db error', err);
if (err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
handleDisconnect(); // lost due to either server restart, or a
} else { // connnection idle timeout (the wait_timeout
throw err; // server variable configures this)
}
});
}
handleDisconnect();
console.log(id);
connection.query("select * from table where id = '"+id+"'", function(err, rows, fields){
if (err){
console.log(err);
throw err;
}
var objToJson = rows;
objToJson.response = response;
var finalresponse = JSON.stringify(objToJson);
response.write('{ "firstdata": ')
response.write(finalresponse);
var jsonResult = JSON.parse(finalresponse);
var ordersplit = jsonResult[0].order_split
if(ordersplit == 0){
connection.query("Call getUnit('"+id+"');", function(err, rows, fields){
if (err){
console.log(err);
throw err;
}
var objToJson = rows[0];
objToJson.response = response;
response.write(', "data": ');
response.write(JSON.stringify(objToJson));
response.write('}');
response.end();
});
}
if(ordersplit == 1){
connection.query("Call getUnitCustomize('"+id+"');", function(err, rows, fields){
if (err){
console.log(err);
throw err;
}
var objToJson = rows[0];
objToJson.response = response;
response.write(', "data": ');
response.write(JSON.stringify(objToJson));
response.write('}');
response.end();
});
}
connection.end();
});