Reputation: 135
I have a small problem. I am trying to perform a simple operation but I keep on getting the same error, I am running out of ideas and I couldn't find anything in the internet...
The portion of code causing the error is the following:
response.write(readDB(no)); // <= this line
response.end();
The readDB function is here:
function readDB(gene){
console.log("test43");
MongoClient.connect(url, function(err, db) {
if(!err) {
console.log("We are connected");
console.log("test44");
var collection = db.collection('links');
var ans= collection.find( { generated: gene}, {original:1, _id:0}, function(err, gg){
console.log("test dat result:"+ans.original);
console.log("acces to:"+ans.original);
var rep
rep.writeHead(200, {"Content-Type": "text/html"});
rep.write("<html>");
rep.write("<head>");
rep.write("<title>Redirection</title>");
rep.write("<meta http-equiv=\"refresh\" content=\"5\"; URL=\""+ans.original+"\">");
rep.write("<script type=\"text/javascript\">window.location.href = \""+ans.original+"\"</script>");
rep.write("</head>");
rep.write("<body>Redirection...");
rep.write("</body>");
rep.write("</html>");
return rep;
})
}
if(err){
//console.log(err)
}
} )};
I know the code is not great, but still... The message "test43" is shown in my console, and after that I keep getting:
_http_outgoing.js:436
throw new TypeError('first argument must be a string or Buffer');
^
TypeError: first argument must be a string or Buffer
If someone could tell me what I am doing wrong it would be great !
Thanks !
Upvotes: 1
Views: 90
Reputation: 30416
The error is telling you that response.write()
is expecting a string
(or Buffer
), but your function readDB
does not return anything there is a callback inside of this function that returns something but this is asynchronously called so your erring line is being read as response.write(undefined)
. Perhaps consider passing the response
object as an argument by changing your readDB
function to look like this:
function readDB(gene, rep){
...
}
then call it like this:
readDB(no, response); // <= this line
You will also need to remove the var rep
inside your function as it will overwrite the passed in response argument (also returning it will not be necessary though there is no side effect that I can think of by unnecessarily returning it). Finally you will want to not call response.end()
right after calling your updated readDB
function because the output generated by the callback will not have had time to execute.
Upvotes: 1