簡體   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

在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!
    });

我知道服務器從URL路由中正確獲取了數據,因為控制台正確顯示了celien (字符串)。 我也知道function articleReturner(celien)正在正確查詢數據庫,因為控制台正確顯示了cetarticle (JSON)。

但是res.render('selection_form.ejs', cetarticle); 無法正常工作,並且控制台顯示ReferenceError: cetarticle is not defined ...我缺少什么? 謝謝!

函數return cetarticle;異步執行並return cetarticle; 沒有任何意義。 您需要使用回調或Promise。 這是使用回調從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