简体   繁体   English

在Node.js Express服务器中处理GET请求:res.render(file.ejs,data)不起作用,因为未定义数据

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

In a server made with Express in Node.js, I have the following code for handling a GET request: 在Node.js中使用Express制造的服务器中,我具有以下代码来处理GET请求:

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). 我知道服务器从URL路由中正确获取了数据,因为控制台正确显示了celien (字符串)。 I also know that the function articleReturner(celien) is correctly querying the database because the console correctly displays cetarticle (a JSON). 我也知道function articleReturner(celien)正在正确查询数据库,因为控制台正确显示了cetarticle (JSON)。

But res.render('selection_form.ejs', cetarticle); 但是res.render('selection_form.ejs', cetarticle); is not working and the console displays ReferenceError: cetarticle is not defined ... What am I missing? 无法正常工作,并且控制台显示ReferenceError: cetarticle is not defined ...我缺少什么? Thanks! 谢谢!

Function articleReturner is executed asynchronously and return cetarticle; 函数return cetarticle;异步执行并return cetarticle; doesn't make a lot of sense. 没有任何意义。 You need to use callbacks or promises. 您需要使用回调或Promise。 Here is the code that uses callback to return result from articleReturner: 这是使用回调从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); 
  });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM