Handling a GET request in Node.js Express server: res.render(file.ejs, data) not working because data is not defined

StackOverflow https://stackoverflow.com/questions/23531685

Question

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!

Was it helpful?

Solution

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); 
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top