When querying a database from Node, how does one pass the HTTP response object to the aysynchronous callback? For example (db stuff is pseudocode):
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
// read from database:
var dbClient = createClient(myCredentials);
var myQuery = 'my query goes here';
dbClient.query(myQuery, callback);
function callback(error, results, response) // Pass 'response' to the callback?
{
if (error === null) {
for (var index in results) response.write(index); // Error
response.end('End of data');
}
else {
response.end('Error querying database.')
}
}
}).listen(1337, "127.0.0.1");
When passing response to the callback, Node gives an error that the results continuation object has no method write.
What’s the best strategy here?
By putting response in the callback function declaration, you are creating a new null response object that has scope only in the callback function.
Instead, all you need to do is remove the response parameter.
And within this callback function, the variable response will now refer to the original response variable of createServer callback. Since this function is inside of the createServer callback, it will have access to the response object.