【问题标题】:how to pass function value如何传递函数值
【发布时间】:2017-07-18 02:23:04
【问题描述】:

我创建了名为 (user.js) 的模型

    module.exports.show_deatils = function(req,res,callback){   
      var resultArray=[];
      mongo.connect(url,function(err,db){
        assert.equal(null,err);
        var cursor=db.collection('users').find();
        cursor.forEach(function(doc,err){
          assert.equal(null,err);
          resultArray.push(doc);         
        });
      });
    }

    router.get('/restful', function(req, res){    
      User.show_deatils(function(req,res,resultArray){
        req.session.resultArray=resultArray;
        console.log(resultArray);
      });
      res.render('restful');
    });

我在模型user.js 中创建了一个method("show_details"),并且我在路由中调用了该特定函数。每当加载页面(restful)时,我都希望显示数据resultArray。但我被困在这里。

你能建议我如何解决这个问题吗?

【问题讨论】:

    标签: node.js express ejs


    【解决方案1】:

    在您的res 对象上,您需要在渲染函数中传递变量resultArray,以便在您的模板中使用它。

    类似:

    res.render('restful', {var_in_ejs_template: resultArray});
    

    这在 express.js 的文档中有详细记录:link

    另外,不要将结果放在res.session 属性中。看起来很脏。

    【讨论】:

    • 在做同样的事情之后 res.render('restful',{items:resultArray}); });这会引发错误 ReferenceError: resultArray is not defined at C:\nodeproject\loginapp\routes\users.js:176:33
    • @riza 未定义,因为您在方法的回调范围之外使用它。
    • @riza 当你调用它时,你的方法没有返回任何 resultArray 对象。
    • module.exports.show_deatils=function(req,res,callback){ var resultArray=[]; mongo.connect(url,function(err,db){ assert.equal(null,err); var cursor=db.collection('users').find(); cursor.forEach(function(doc,err){ assert .equal(null,err); resultArray.push(doc); }); });返回结果数组;返回 resultArray 后,我仍然无法获取值。我对 node.js 很陌生。你能帮帮我吗。
    【解决方案2】:

    你的用户模块 show_deatils 有两个参数,你没有传递任何参数, 在你没有使用的回调中,

    user.js

    module.exports.show_deatils = function(req,res,callback){   
          var resultArray=[];
          mongo.connect(url,function(err,db){
            assert.equal(null,err);
            var cursor=db.collection('users').find();
            cursor.forEach(function(doc,err){
              assert.equal(null,err);
              resultArray.push(doc);         
            });
            callback(resultArray);
          });
        }
    

    路线

     router.get('/restful', function(req, res){    
          User.show_deatils(req,res,function(resultArray){
            req.session.resultArray=resultArray;
            console.log(resultArray);
            res.render('restful');
          });
    
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 2010-09-25
      • 2018-12-17
      • 2021-05-19
      • 2016-05-16
      • 1970-01-01
      • 2022-12-04
      相关资源
      最近更新 更多