In a server made with Express in Node.js, I have the following code for handling a GET request:
function articleReturner(celien) { // function querying a database (celien is a string, cetarticle is a JSON)
Article.findOne({ lien: celien}, function (err, cetarticle){
console.log(cetarticle); // it works
return cetarticle;
});
}
app.get('/selection/oui/', function(req, res) { // the URL requested ends with ?value=http://sweetrandoms.com, for example
var celien = req.param("value"); //
console.log(celien); // it works
articleReturner(celien); // calling the function defined above
res.render('selection_form.ejs', cetarticle); // doesn't work!
});
I know that data from the URL routing is correctly obtained by the server since the console correctly displays celien
(a string). I also know that the function articleReturner(celien)
is correctly querying the database because the console correctly displays cetarticle
(a JSON).
But res.render('selection_form.ejs', cetarticle);
is not working and the console displays ReferenceError: cetarticle is not defined
... What am I missing? Thanks!
Function articleReturner is executed asynchronously and return cetarticle;
doesn't make a lot of sense. You need to use callbacks or promises. Here is the code that uses callback to return result from articleReturner:
function articleReturner(celien, callback) {
Article.findOne({ lien: celien}, function (err, cetarticle){
console.log(cetarticle);
callback(err,cetarticle);
});
}
app.get('/selection/oui/', function(req, res) {
var celien = req.param("value"); //
console.log(celien); // it works
articleReturner(celien, function(err, cetarticle){
res.render('selection_form.ejs', cetarticle);
});
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.